@Properties(inherit=javacpp.class) public class Pointer extends Object implements AutoCloseable
void*
, which can point to any
struct
, class
, or union
. All Pointer classes get parsed
by Generator
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 the AutoCloseable
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:
BytePointer
,
ShortPointer
,
IntPointer
,
LongPointer
,
FloatPointer
,
DoublePointer
,
CharPointer
,
PointerPointer
,
BoolPointer
,
CLongPointer
,
SizeTPointer
Modifier and Type | Class and Description |
---|---|
protected static class |
Pointer.CustomDeallocator
A
Pointer.Deallocator that calls, during garbage collection, a method with signature
static 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 of
PhantomReference 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
A
Pointer.Deallocator that calls, during garbage collection, a native function. |
(package private) static class |
Pointer.ProxyDeallocator
A
Pointer.Deallocator that keeps and uses a strong reference to a Buffer or another Pointer. |
protected static interface |
Pointer.ReferenceCounter |
Modifier and Type | Field and 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 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 to
System.gc() . |
(package private) static long |
maxPhysicalBytes
Maximum amount of memory reported by
physicalBytes() before forcing call to System.gc() . |
(package private) static int |
maxRetries
Maximum number of times to call
System.gc() before giving up with OutOfMemoryError . |
protected long |
position
The index of the element of a native array that should be accessed.
|
private static ReferenceQueue<Pointer> |
referenceQueue
The
ReferenceQueue used by Pointer.DeallocatorReference . |
Constructor and Description |
---|
Pointer()
Default constructor that does nothing.
|
Pointer(Buffer b)
Copies the address, position, limit, and capacity of a direct NIO
Buffer . |
Pointer(Pointer p)
Copies the address, position, limit, and capacity of another Pointer.
|
Modifier and Type | Method and Description |
---|---|
long |
address()
Returns
address . |
private void |
allocate(Buffer b) |
Buffer |
asBuffer()
Same as
asByteBuffer() , but can be overridden to return subclasses of Buffer. |
ByteBuffer |
asByteBuffer()
|
private 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()
Returns
capacity . |
<P extends Pointer> |
capacity(long capacity)
Sets the capacity and returns this.
|
void |
close()
Calls
releaseReference() . |
void |
deallocate()
Calls
deallocate(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 the
referenceQueue . |
protected Pointer.Deallocator |
deallocator()
Returns
deallocator . |
protected <P extends Pointer> |
deallocator(Pointer.Deallocator deallocator)
Sets the deallocator and returns this.
|
boolean |
equals(Object obj)
Checks for equality with argument.
|
<P extends Pointer> |
fill(int b)
Calls in effect
memset(address + position, b, length) ,
where length = sizeof() * (limit - position) . |
static 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(Buffer b)
Returns the starting address of the memory region referenced by the given direct
Buffer . |
<P extends Pointer> |
getPointer()
Returns
getPointer(0) . |
<P extends Pointer> |
getPointer(Class<P> type)
Returns
getPointer(type, 0) . |
<P extends Pointer> |
getPointer(Class<P> type,
long i)
|
<P extends Pointer> |
getPointer(long i)
Returns
getPointer(getClass(), 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()
Calls
deallocatorThread.interrupt() . |
boolean |
isNull()
Returns
address == 0 . |
static boolean |
isNull(Pointer p)
Returns
p == null || p.address == 0 . |
long |
limit()
Returns
limit . |
<P extends Pointer> |
limit(long limit)
Sets the limit and returns this.
|
static Pointer |
malloc(long size) |
static long |
maxBytes()
Returns
maxBytes , the maximum amount of memory allowed to be tracked. |
static long |
maxPhysicalBytes()
Returns
maxPhysicalBytes , 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> |
offsetAddress(long i)
|
static int |
offsetof(Class<? extends Pointer> type,
String member)
Returns
Loader.offsetof(type, member) . |
int |
offsetof(String member)
Returns
Loader.offsetof(getClass(), member) or -1 on error. |
static long |
parseBytes(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 than
physicalBytes() but less than maxSize to save processing time. |
long |
position()
Returns
position . |
<P extends Pointer> |
position(long position)
Sets the position and returns this.
|
<P extends Pointer> |
put(Pointer p)
Calls in effect
memcpy(this.address + this.position, p.address + p.position, length) ,
where length = sizeof(p) * (p.limit - p.position) . |
static Pointer |
realloc(Pointer p,
long size) |
int |
referenceCount()
Returns
Pointer.ReferenceCounter.count() or -1 if no deallocator has been set. |
boolean |
releaseReference()
Calls
Pointer.ReferenceCounter.release() , decrementing the reference count by 1,
in turn deallocating this Pointer when the count drops to 0. |
<P extends Pointer> |
retainReference()
Calls
Pointer.ReferenceCounter.retain() , incrementing the reference count by 1. |
void |
setNull()
Sets
address to 0. |
int |
sizeof()
Returns 1 for Pointer or BytePointer else
Loader.sizeof(getClass()) or -1 on error. |
static int |
sizeof(Class<? extends Pointer> type)
Returns
Loader.sizeof(type) . |
String |
toString()
|
static long |
totalBytes()
Returns
totalBytes() , current amount of memory tracked by deallocators. |
static long |
totalCount()
Returns
totalCount() , 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> |
withDeallocator(P p)
A utility method to register easily a
Pointer.CustomDeallocator with a Pointer. |
<P extends Pointer> |
zero()
Returns
fill(0) . |
private static final Logger logger
private static final ReferenceQueue<Pointer> referenceQueue
ReferenceQueue
used by Pointer.DeallocatorReference
.
Initialized to null if the "org.bytedeco.javacpp.noPointerGC" system property is "true".static final Thread deallocatorThread
static final long maxBytes
System.gc()
.
Set via "org.bytedeco.javacpp.maxBytes" system property, defaults to Runtime.maxMemory()
.
The value is parsed with parseBytes(String, long)
where relativeMultiple = Runtime.maxMemory()
.
We can use a value of 0 or less to prevent any explicit call to the garbage collector.static final long maxPhysicalBytes
physicalBytes()
before forcing call to System.gc()
.
Set via "org.bytedeco.javacpp.maxPhysicalBytes" system property, defaults to maxBytes > 0 ? maxBytes + 3 * Runtime.maxMemory() : 0
.
If maxBytes
is also not set, this is equivalent to a default of 4 * Runtime.maxMemory()
.
The value is parsed with parseBytes(String, long)
where relativeMultiple = Runtime.maxMemory()
.
We can use a value of 0 or less to prevent any explicit call to the garbage collector.static final int maxRetries
System.gc()
before giving up with OutOfMemoryError
.
Set via "org.bytedeco.javacpp.maxRetries" system property, defaults to 10, where each retry is followed
by a call to Thread.sleep(100)
and Pointer.trimMemory()
.protected long address
protected long position
protected long limit
protected long capacity
private Pointer.Deallocator deallocator
public Pointer()
public Pointer(Pointer p)
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.
p
- the other Pointer to referenceprivate void allocate(Buffer b)
void init(long allocatedAddress, long allocatedCapacity, long ownerAddress, long deallocatorAddress)
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 functionPointer.NativeDeallocator
protected <P extends Pointer> P offsetAddress(long i)
protected static <P extends Pointer> P withDeallocator(P p)
Pointer.CustomDeallocator
with a Pointer.p
- the Pointer with which to register the deallocatorpublic static String formatBytes(long bytes)
public static long parseBytes(String string, long relativeMultiple) throws NumberFormatException
string
- to parserelativeMultiple
- to use in the case of "%", which is divided by 100NumberFormatException
public static void interruptDeallocatorThread()
deallocatorThread.interrupt()
.public static void deallocateReferences()
referenceQueue
.public static long maxBytes()
maxBytes
, the maximum amount of memory allowed to be tracked.public static long totalBytes()
totalBytes()
, current amount of memory tracked by deallocators.public static long totalCount()
totalCount()
, current number of pointers tracked by deallocators.public static long maxPhysicalBytes()
maxPhysicalBytes
, the maximum amount of physical memory that should be used.@Name(value="JavaCPP_trimMemory") private static boolean trimMemory()
@Name(value="JavaCPP_physicalBytes") public static long physicalBytes()
@Name(value="JavaCPP_physicalBytes") public static long physicalBytesInaccurate(long maxSize)
physicalBytes()
but less than maxSize
to save processing time.@Name(value="JavaCPP_totalPhysicalBytes") public static long totalPhysicalBytes()
physicalBytes()
to go over this value.@Name(value="JavaCPP_availablePhysicalBytes") public static long availablePhysicalBytes()
@Name(value="JavaCPP_getDirectBufferAddress") protected static long getDirectBufferAddress(@Raw(withEnv=true) Buffer b)
Buffer
.
An alternative to allocating a new Pointer object if all you need is the memory address.public static boolean isNull(Pointer p)
p == null || p.address == 0
.public boolean isNull()
address == 0
.public void setNull()
address
to 0.public long address()
address
.public long position()
position
.public <P extends Pointer> P position(long position)
array.position(i)
statement sort of equivalent to the array[i]
statement in C++.position
- the new positionpublic long limit()
limit
.public <P extends Pointer> P limit(long limit)
limit
- the new limitpublic long capacity()
capacity
.public <P extends Pointer> P capacity(long capacity)
capacity
- the new capacityprotected Pointer.Deallocator deallocator()
deallocator
.protected <P extends Pointer> P deallocator(Pointer.Deallocator deallocator)
null
. That is, it deallocates previously allocated memory.
Should not be called more than once after allocation.deallocator
- the new deallocatorpublic void close()
releaseReference()
.close
in interface AutoCloseable
public void deallocate()
deallocate(true)
.public void deallocate(boolean deallocate)
deallocator(Deallocator)
.deallocate
- if true, deallocates, else does not, but disables garbage collectionpublic <P extends Pointer> P retainReference()
Pointer.ReferenceCounter.retain()
, incrementing the reference count by 1.
Has no effect if no deallocator was previously set with deallocator(Deallocator)
.public boolean releaseReference()
Pointer.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 with deallocator(Deallocator)
.public int referenceCount()
Pointer.ReferenceCounter.count()
or -1 if no deallocator has been set.public static int offsetof(Class<? extends Pointer> type, String member)
Loader.offsetof(type, member)
.public int offsetof(String member)
Loader.offsetof(getClass(), member)
or -1 on error.public int sizeof()
Loader.sizeof(getClass())
or -1 on error.private ByteBuffer asDirectBuffer()
public ByteBuffer asByteBuffer()
ByteBuffer
covering the memory space between the
position
and limit
of this Pointer. The way the methods
were designed allows constructs such as
this.position(13).limit(42).asByteBuffer()
.
The new buffer's position will be equal to position
, its capacity
and its limit will be equal to limit
, and its mark will be
undefined. In the event that limit <= 0
, the capacity and limit will
be set to position + 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:
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)
}
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.getPointer(Integer.MAX_VALUE)
.asByteBuffer();
buffer.position(); // 0
buffer.capacity(); // 1
buffer.remaining(); // 1
}
ByteBuffer
createdByteBuffer.isDirect()
,
getPointer(long)
public Buffer asBuffer()
asByteBuffer()
, but can be overridden to return subclasses of Buffer.asByteBuffer()
BytePointer.asBuffer()
,
ShortPointer.asBuffer()
,
IntPointer.asBuffer()
,
LongPointer.asBuffer()
,
FloatPointer.asBuffer()
,
DoublePointer.asBuffer()
,
CharPointer.asBuffer()
public static Pointer malloc(long size)
public static Pointer calloc(long n, long size)
public static void free(Pointer p)
public <P extends Pointer> P getPointer()
getPointer(0)
.public <P extends Pointer> P getPointer(long i)
getPointer(getClass(), i)
.public <P extends Pointer> P put(Pointer p)
memcpy(this.address + this.position, p.address + p.position, length)
,
where length = sizeof(p) * (p.limit - p.position)
.
If limit == 0, it uses position + 1 instead. The way the methods were designed
allows constructs such as this.position(0).put(p.position(13).limit(42))
.p
- the Pointer from which to copy memorypublic <P extends Pointer> P fill(int b)
memset(address + position, b, length)
,
where length = sizeof() * (limit - position)
.
If limit == 0, it uses position + 1 instead. The way the methods were designed
allows constructs such as this.position(0).limit(13).fill(42)
;b
- the byte value to fill the memory withpublic <P extends Pointer> P zero()
fill(0)
.public boolean equals(Object obj)
(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.Copyright © 2024. All rights reserved.