Class Pointer
- java.lang.Object
-
- org.bytedeco.javacpp.Pointer
-
- All Implemented Interfaces:
java.lang.AutoCloseable
- Direct Known Subclasses:
BooleanPointer
,BoolPointer
,BytePointer
,CharPointer
,CLongPointer
,DoublePointer
,FloatPointer
,FunctionPointer
,IntPointer
,LongPointer
,PointerPointer
,ShortPointer
,SizeTPointer
@Properties(inherit=javacpp.class) public class Pointer extends java.lang.Object implements java.lang.AutoCloseable
All peer classes to native types must be descended from Pointer, the topmost class. It can be thought as mapping the native C++void*
, which can point to anystruct
,class
, orunion
. All Pointer classes get parsed byGenerator
to produce proper wrapping JNI code, but this base class also provides functionality to access native array elements as well as utility methods and classes to let users benefit not only from from garbage collection, but also the try-with-resources statement, since it implements theAutoCloseable
interface.It is also possible to use a
PointerScope
to keep track of a group of Pointer objects, and have them deallocated in a transparent but deterministic manner.For examples of subclasses, please refer to the following:
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static class
Pointer.CustomDeallocator
APointer.Deallocator
that calls, during garbage collection, a method with signaturestatic void deallocate()
from the Pointer object passed to the constructor and that accepts it as argument.protected static interface
Pointer.Deallocator
The interface to implement to produce a Deallocator usable by Pointer.(package private) static class
Pointer.DeallocatorReference
A subclass ofPhantomReference
that also acts as a linked list to keep their references alive until they get garbage collected.(package private) static class
Pointer.DeallocatorThread
protected static class
Pointer.NativeDeallocator
APointer.Deallocator
that calls, during garbage collection, a native function.(package private) static class
Pointer.ProxyDeallocator
APointer.Deallocator
that keeps and uses a strong reference to a Buffer or another Pointer.protected static interface
Pointer.ReferenceCounter
-
Field Summary
Fields Modifier and Type Field Description protected long
address
The native address of this Pointer, which can be an array.protected long
capacity
The number of elements contained in this native array, or 0 if unknown.private Pointer.Deallocator
deallocator
The deallocator associated with this Pointer that should be called on garbage collection.(package private) static java.lang.Thread
deallocatorThread
protected long
limit
The index of the first element that should not be accessed, or 0 if unknown.private static Logger
logger
(package private) static long
maxBytes
Maximum amount of memory registered with live deallocators before forcing call toSystem.gc()
.(package private) static long
maxPhysicalBytes
Maximum amount of memory reported byphysicalBytes()
before forcing call toSystem.gc()
.(package private) static int
maxRetries
Maximum number of times to callSystem.gc()
before giving up withOutOfMemoryError
.protected long
position
The index of the element of a native array that should be accessed.private static java.lang.ref.ReferenceQueue<Pointer>
referenceQueue
TheReferenceQueue
used byPointer.DeallocatorReference
.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description long
address()
Returnsaddress
.private void
allocate(java.nio.Buffer b)
java.nio.Buffer
asBuffer()
Same asasByteBuffer()
, but can be overridden to return subclasses of Buffer.java.nio.ByteBuffer
asByteBuffer()
private java.nio.ByteBuffer
asDirectBuffer()
static long
availablePhysicalBytes()
Returns the amount of physical memory that is free according to the operating system, or 0 if unknown.static Pointer
calloc(long n, long size)
long
capacity()
Returnscapacity
.<P extends Pointer>
Pcapacity(long capacity)
Sets the capacity and returns this.void
close()
CallsreleaseReference()
.void
deallocate()
Callsdeallocate(true)
.void
deallocate(boolean deallocate)
Explicitly manages native memory without waiting after the garbage collector.static void
deallocateReferences()
Clears, deallocates, and removes all garbage collected objects from thereferenceQueue
.protected Pointer.Deallocator
deallocator()
Returnsdeallocator
.protected <P extends Pointer>
Pdeallocator(Pointer.Deallocator deallocator)
Sets the deallocator and returns this.boolean
equals(java.lang.Object obj)
Checks for equality with argument.<P extends Pointer>
Pfill(int b)
Calls in effectmemset(address + position, b, length)
, wherelength = sizeof() * (limit - position)
.static java.lang.String
formatBytes(long bytes)
Truncates and formats the number of bytes to a human readable string ending with "T", "G", "M", or "K" (as multiples of 1024).static void
free(Pointer p)
protected static long
getDirectBufferAddress(java.nio.Buffer b)
Returns the starting address of the memory region referenced by the given directBuffer
.<P extends Pointer>
PgetPointer()
ReturnsgetPointer(0)
.<P extends Pointer>
PgetPointer(long i)
ReturnsgetPointer(getClass(), i)
.<P extends Pointer>
PgetPointer(java.lang.Class<P> type)
ReturnsgetPointer(type, 0)
.<P extends Pointer>
PgetPointer(java.lang.Class<P> type, long i)
int
hashCode()
Returns(int)address
.(package private) void
init(long allocatedAddress, long allocatedCapacity, long ownerAddress, long deallocatorAddress)
Called by native libraries to initialize the object fields.static void
interruptDeallocatorThread()
CallsdeallocatorThread.interrupt()
.boolean
isNull()
Returnsaddress == 0
.static boolean
isNull(Pointer p)
Returnsp == null || p.address == 0
.long
limit()
Returnslimit
.<P extends Pointer>
Plimit(long limit)
Sets the limit and returns this.static Pointer
malloc(long size)
static long
maxBytes()
ReturnsmaxBytes
, the maximum amount of memory allowed to be tracked.static long
maxPhysicalBytes()
ReturnsmaxPhysicalBytes
, the maximum amount of physical memory that should be used.static Pointer
memchr(Pointer p, int ch, long size)
static int
memcmp(Pointer p1, Pointer p2, long size)
static Pointer
memcpy(Pointer dst, Pointer src, long size)
static Pointer
memmove(Pointer dst, Pointer src, long size)
static Pointer
memset(Pointer dst, int ch, long size)
protected <P extends Pointer>
PoffsetAddress(long i)
static int
offsetof(java.lang.Class<? extends Pointer> type, java.lang.String member)
ReturnsLoader.offsetof(type, member)
.int
offsetof(java.lang.String member)
ReturnsLoader.offsetof(getClass(), member)
or -1 on error.static long
parseBytes(java.lang.String string, long relativeMultiple)
Returns the amount of bytes for a number possibly ending with "%", "t", "g", m", or "k" (as multiples of 1024).static long
physicalBytes()
Returns the amount of non-shared physical memory currently used by the whole process, or 0 if unknown.static long
physicalBytesInaccurate(long maxSize)
May return a value larger thanphysicalBytes()
but less thanmaxSize
to save processing time.long
position()
Returnsposition
.<P extends Pointer>
Pposition(long position)
Sets the position and returns this.<P extends Pointer>
Pput(Pointer p)
Calls in effectmemcpy(this.address + this.position, p.address + p.position, length)
, wherelength = sizeof(p) * (p.limit - p.position)
.static Pointer
realloc(Pointer p, long size)
int
referenceCount()
ReturnsPointer.ReferenceCounter.count()
or -1 if no deallocator has been set.boolean
releaseReference()
CallsPointer.ReferenceCounter.release()
, decrementing the reference count by 1, in turn deallocating this Pointer when the count drops to 0.<P extends Pointer>
PretainReference()
CallsPointer.ReferenceCounter.retain()
, incrementing the reference count by 1.void
setNull()
Setsaddress
to 0.int
sizeof()
Returns 1 for Pointer or BytePointer elseLoader.sizeof(getClass())
or -1 on error.static int
sizeof(java.lang.Class<? extends Pointer> type)
ReturnsLoader.sizeof(type)
.java.lang.String
toString()
static long
totalBytes()
ReturnstotalBytes()
, current amount of memory tracked by deallocators.static long
totalCount()
ReturnstotalCount()
, current number of pointers tracked by deallocators.static long
totalPhysicalBytes()
Returns the amount of physical memory installed according to the operating system, or 0 if unknown.private static boolean
trimMemory()
Makes sure to return freed memory to the system, as required by Linux, at least.protected static <P extends Pointer>
PwithDeallocator(P p)
A utility method to register easily aPointer.CustomDeallocator
with a Pointer.<P extends Pointer>
Pzero()
Returnsfill(0)
.
-
-
-
Field Detail
-
logger
private static final Logger logger
-
referenceQueue
private static final java.lang.ref.ReferenceQueue<Pointer> referenceQueue
TheReferenceQueue
used byPointer.DeallocatorReference
. Initialized to null if the "org.bytedeco.javacpp.noPointerGC" system property is "true".
-
deallocatorThread
static final java.lang.Thread deallocatorThread
-
maxBytes
static final long maxBytes
Maximum amount of memory registered with live deallocators before forcing call toSystem.gc()
. Set via "org.bytedeco.javacpp.maxBytes" system property, defaults toRuntime.maxMemory()
. The value is parsed withparseBytes(String, long)
whererelativeMultiple = Runtime.maxMemory()
. We can use a value of 0 or less to prevent any explicit call to the garbage collector.
-
maxPhysicalBytes
static final long maxPhysicalBytes
Maximum amount of memory reported byphysicalBytes()
before forcing call toSystem.gc()
. Set via "org.bytedeco.javacpp.maxPhysicalBytes" system property, defaults tomaxBytes > 0 ? maxBytes + 3 * Runtime.maxMemory() : 0
. IfmaxBytes
is also not set, this is equivalent to a default of4 * Runtime.maxMemory()
. The value is parsed withparseBytes(String, long)
whererelativeMultiple = Runtime.maxMemory()
. We can use a value of 0 or less to prevent any explicit call to the garbage collector.
-
maxRetries
static final int maxRetries
Maximum number of times to callSystem.gc()
before giving up withOutOfMemoryError
. Set via "org.bytedeco.javacpp.maxRetries" system property, defaults to 10, where each retry is followed by a call toThread.sleep(100)
andPointer.trimMemory()
.
-
address
protected long address
The native address of this Pointer, which can be an array.
-
position
protected long position
The index of the element of a native array that should be accessed.
-
limit
protected long limit
The index of the first element that should not be accessed, or 0 if unknown.
-
capacity
protected long capacity
The number of elements contained in this native array, or 0 if unknown.
-
deallocator
private Pointer.Deallocator deallocator
The deallocator associated with this Pointer that should be called on garbage collection.
-
-
Constructor Detail
-
Pointer
public Pointer()
Default constructor that does nothing.
-
Pointer
public Pointer(Pointer p)
Copies the address, position, limit, and capacity of another Pointer. Also keeps a reference to it to prevent its memory from getting deallocated.This copy constructor basically acts as a
reinterpret_cast
, at least on plain old data (POD)struct
, so we need to be careful with it.- Parameters:
p
- the other Pointer to reference
-
Pointer
public Pointer(java.nio.Buffer b)
Copies the address, position, limit, and capacity of a direct NIOBuffer
. Also keeps a reference to it to prevent its memory from getting deallocated.- Parameters:
b
- the Buffer object to reference
-
-
Method Detail
-
allocate
private void allocate(java.nio.Buffer b)
-
init
void init(long allocatedAddress, long allocatedCapacity, long ownerAddress, long deallocatorAddress)
Called by native libraries to initialize the object fields.- Parameters:
allocatedAddress
- the new address value of allocated native memoryallocatedCapacity
- the amount of elements allocated (initial limit and capacity)deallocatorAddress
- the pointer to the native deallocation function- See Also:
Pointer.NativeDeallocator
-
offsetAddress
protected <P extends Pointer> P offsetAddress(long i)
-
withDeallocator
protected static <P extends Pointer> P withDeallocator(P p)
A utility method to register easily aPointer.CustomDeallocator
with a Pointer.- Parameters:
p
- the Pointer with which to register the deallocator- Returns:
- the Pointer
-
formatBytes
public static java.lang.String formatBytes(long bytes)
Truncates and formats the number of bytes to a human readable string ending with "T", "G", "M", or "K" (as multiples of 1024).
-
parseBytes
public static long parseBytes(java.lang.String string, long relativeMultiple) throws java.lang.NumberFormatException
Returns the amount of bytes for a number possibly ending with "%", "t", "g", m", or "k" (as multiples of 1024). May also be suffixed with an optional "b", where all letters are case-insensitive.- Parameters:
string
- to parserelativeMultiple
- to use in the case of "%", which is divided by 100- Returns:
- the amount of bytes
- Throws:
java.lang.NumberFormatException
-
interruptDeallocatorThread
public static void interruptDeallocatorThread()
CallsdeallocatorThread.interrupt()
.
-
deallocateReferences
public static void deallocateReferences()
Clears, deallocates, and removes all garbage collected objects from thereferenceQueue
.
-
maxBytes
public static long maxBytes()
ReturnsmaxBytes
, the maximum amount of memory allowed to be tracked.
-
totalBytes
public static long totalBytes()
ReturnstotalBytes()
, current amount of memory tracked by deallocators.
-
totalCount
public static long totalCount()
ReturnstotalCount()
, current number of pointers tracked by deallocators.
-
maxPhysicalBytes
public static long maxPhysicalBytes()
ReturnsmaxPhysicalBytes
, the maximum amount of physical memory that should be used.
-
trimMemory
@Name("JavaCPP_trimMemory") private static boolean trimMemory()
Makes sure to return freed memory to the system, as required by Linux, at least.
-
physicalBytes
@Name("JavaCPP_physicalBytes") public static long physicalBytes()
Returns the amount of non-shared physical memory currently used by the whole process, or 0 if unknown. Also known as "anonymous resident set size" (Linux, Mac OS X, etc) or "private working set size" (Windows).
-
physicalBytesInaccurate
@Name("JavaCPP_physicalBytes") public static long physicalBytesInaccurate(long maxSize)
May return a value larger thanphysicalBytes()
but less thanmaxSize
to save processing time.
-
totalPhysicalBytes
@Name("JavaCPP_totalPhysicalBytes") public static long totalPhysicalBytes()
Returns the amount of physical memory installed according to the operating system, or 0 if unknown. It should not be possible forphysicalBytes()
to go over this value.
-
availablePhysicalBytes
@Name("JavaCPP_availablePhysicalBytes") public static long availablePhysicalBytes()
Returns the amount of physical memory that is free according to the operating system, or 0 if unknown.
-
getDirectBufferAddress
@Name("JavaCPP_getDirectBufferAddress") protected static long getDirectBufferAddress(@Raw(withEnv=true) java.nio.Buffer b)
Returns the starting address of the memory region referenced by the given directBuffer
. An alternative to allocating a new Pointer object if all you need is the memory address.
-
isNull
public static boolean isNull(Pointer p)
Returnsp == null || p.address == 0
.
-
isNull
public boolean isNull()
Returnsaddress == 0
.
-
setNull
public void setNull()
Setsaddress
to 0.
-
address
public long address()
Returnsaddress
.
-
position
public long position()
Returnsposition
.
-
position
public <P extends Pointer> P position(long position)
Sets the position and returns this. That makes thearray.position(i)
statement sort of equivalent to thearray[i]
statement in C++.- Parameters:
position
- the new position- Returns:
- this
-
limit
public long limit()
Returnslimit
.
-
limit
public <P extends Pointer> P limit(long limit)
Sets the limit and returns this. Used to limit the size of an operation on this object.- Parameters:
limit
- the new limit- Returns:
- this
-
capacity
public long capacity()
Returnscapacity
.
-
capacity
public <P extends Pointer> P capacity(long capacity)
Sets the capacity and returns this. Should not be called more than once after allocation.- Parameters:
capacity
- the new capacity- Returns:
- this
-
deallocator
protected Pointer.Deallocator deallocator()
Returnsdeallocator
.
-
deallocator
protected <P extends Pointer> P deallocator(Pointer.Deallocator deallocator)
Sets the deallocator and returns this. Also clears current deallocator if notnull
. That is, it deallocates previously allocated memory. Should not be called more than once after allocation.- Parameters:
deallocator
- the new deallocator- Returns:
- this
-
close
public void close()
CallsreleaseReference()
.- Specified by:
close
in interfacejava.lang.AutoCloseable
-
deallocate
public void deallocate()
Callsdeallocate(true)
.
-
deallocate
public void deallocate(boolean deallocate)
Explicitly manages native memory without waiting after the garbage collector. Has no effect if no deallocator was previously set withdeallocator(Deallocator)
.- Parameters:
deallocate
- if true, deallocates, else does not, but disables garbage collection
-
retainReference
public <P extends Pointer> P retainReference()
CallsPointer.ReferenceCounter.retain()
, incrementing the reference count by 1. Has no effect if no deallocator was previously set withdeallocator(Deallocator)
.- Returns:
- this
-
releaseReference
public boolean releaseReference()
CallsPointer.ReferenceCounter.release()
, decrementing the reference count by 1, in turn deallocating this Pointer when the count drops to 0. Has no effect if no deallocator was previously set withdeallocator(Deallocator)
.- Returns:
- true when the count drops to 0 and deallocation has occurred
-
referenceCount
public int referenceCount()
ReturnsPointer.ReferenceCounter.count()
or -1 if no deallocator has been set.
-
offsetof
public static int offsetof(java.lang.Class<? extends Pointer> type, java.lang.String member)
ReturnsLoader.offsetof(type, member)
.
-
offsetof
public int offsetof(java.lang.String member)
ReturnsLoader.offsetof(getClass(), member)
or -1 on error.
-
sizeof
public static int sizeof(java.lang.Class<? extends Pointer> type)
ReturnsLoader.sizeof(type)
.
-
sizeof
public int sizeof()
Returns 1 for Pointer or BytePointer elseLoader.sizeof(getClass())
or -1 on error.
-
asDirectBuffer
private java.nio.ByteBuffer asDirectBuffer()
-
asByteBuffer
public java.nio.ByteBuffer asByteBuffer()
Creates a newByteBuffer
covering the memory space between theposition
andlimit
of this Pointer. The way the methods were designed allows constructs such asthis.position(13).limit(42).asByteBuffer()
.The new buffer's position will be equal to
position
, its capacity and its limit will be equal tolimit
, and its mark will be undefined. In the event thatlimit <= 0
, the capacity and limit will be set toposition + 1
. The new buffer will be direct and mutable.NOTE: ByteBuffer objects can only support a capacity of size
Integer.MAX_VALUE
. Certain combinations of position and limit can be greater than the supported capacity. For example, the following code snippet initializes a BytePointer and attempts to make a ByteBuffer from the final element:
In order to access this memory location using a ByteBuffer, you must first offset this pointer's address. See the example below:final long bigSize = Integer.MAX_VALUE + 1L; try (BytePointer pointer = new BytePointer(bigSize)) { pointer.fill(1); pointer.put(pointer.capacity() - 1L, (byte)100); ByteBuffer buffer = pointer.position(Integer.MAX_VALUE) .asByteBuffer(); buffer.position(); // 2147483647 buffer.capacity(); // 2147483647 (error: off by 1) buffer.remaining(); // 0 (error: off by 1) }
final long bigSize = Integer.MAX_VALUE + 1L; try (BytePointer pointer = new BytePointer(bigSize)) { pointer.fill(1); pointer.put(pointer.capacity() - 1L, (byte)100); ByteBuffer buffer = pointer.getPointer(Integer.MAX_VALUE) .asByteBuffer(); buffer.position(); // 0 buffer.capacity(); // 1 buffer.remaining(); // 1 }
- Returns:
- the direct NIO
ByteBuffer
created - See Also:
ByteBuffer.isDirect()
,getPointer(long)
-
asBuffer
public java.nio.Buffer asBuffer()
Same asasByteBuffer()
, but can be overridden to return subclasses of Buffer.- Returns:
asByteBuffer()
- See Also:
BytePointer.asBuffer()
,ShortPointer.asBuffer()
,IntPointer.asBuffer()
,LongPointer.asBuffer()
,FloatPointer.asBuffer()
,DoublePointer.asBuffer()
,CharPointer.asBuffer()
-
malloc
public static Pointer malloc(long size)
-
calloc
public static Pointer calloc(long n, long size)
-
free
public static void free(Pointer p)
-
getPointer
public <P extends Pointer> P getPointer()
ReturnsgetPointer(0)
.
-
getPointer
public <P extends Pointer> P getPointer(long i)
ReturnsgetPointer(getClass(), i)
.
-
getPointer
public <P extends Pointer> P getPointer(java.lang.Class<P> type)
ReturnsgetPointer(type, 0)
.
-
getPointer
public <P extends Pointer> P getPointer(java.lang.Class<P> type, long i)
-
put
public <P extends Pointer> P put(Pointer p)
Calls in effectmemcpy(this.address + this.position, p.address + p.position, length)
, wherelength = sizeof(p) * (p.limit - p.position)
. If limit == 0, it uses position + 1 instead. The way the methods were designed allows constructs such asthis.position(0).put(p.position(13).limit(42))
.- Parameters:
p
- the Pointer from which to copy memory- Returns:
- this
-
fill
public <P extends Pointer> P fill(int b)
Calls in effectmemset(address + position, b, length)
, wherelength = sizeof() * (limit - position)
. If limit == 0, it uses position + 1 instead. The way the methods were designed allows constructs such asthis.position(0).limit(13).fill(42)
;- Parameters:
b
- the byte value to fill the memory with- Returns:
- this
-
zero
public <P extends Pointer> P zero()
Returnsfill(0)
.
-
equals
public boolean equals(java.lang.Object obj)
Checks for equality with argument. Defines obj to be equal if(obj == null && this.address == 0) || (obj.address == this.address && obj.position == this.position)
, and the classes are the same, unless one of them in Pointer itself.- Overrides:
equals
in classjava.lang.Object
- Parameters:
obj
- the object to compare this Pointer to- Returns:
- true if obj is equal
-
hashCode
public int hashCode()
Returns(int)address
.- Overrides:
hashCode
in classjava.lang.Object
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
-