NativeArray<T> wraps a contiguous native memory buffer as a type-safe indexable Java array.
- VarHandle Fast Paths: Uses FFM's sequence element
VarHandleinternally for optimal access speeds. - Bounds Checking: Prevents segmentation faults by asserting bounds on the Java side.
import io.github.undeffineddev.ffmkit.memory.MemoryScope;
import io.github.undeffineddev.ffmkit.memory.NativeArray;
try (MemoryScope scope = MemoryScope.open()) {
// Allocates and populates an array with 4 integers
NativeArray<Integer> arr = scope.arrayOf(1, 2, 3, 4);
// Read elements
int val = arr.get(2); // 3
// Write elements
arr.set(0, 99);
// Iterate
for (int i = 0; i < arr.length(); i++) {
System.out.println(arr.get(i));
}
}NativeArray<T> owns a fixed-length, contiguous native sequence. Its segment() is
the pointer to the first element, so it can be passed to C APIs expecting T*.
Create an array through either the scope or the convenience factories:
try (MemoryScope scope = MemoryScope.open()) {
NativeArray<Integer> numbers = NativeArray.arrayOf(scope, 1, 2, 3);
// Equivalent: scope.arrayOf(1, 2, 3)
numbers.get(0); // 1
numbers.set(1, 42);
numbers.segment(); // int* pointing at the first element
}Factory overloads are available for int, long, float, and double elements.