Sub topic 2
Describing Structs and Arrays with Memory Layouts
This chapter assumes solid Java, basic MethodHandle knowledge, and basic C knowledge. It also assumes JDK 22 or later.
A memory layout describes the shape of native data without allocating it. A StructLayout models a C struct. A sequence layout models a fixed-size C array. An allocated MemorySegment then stores values that follow that description.
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class LayoutDemo {
static final StructLayout POINT = MemoryLayout.structLayout(
ValueLayout.JAVA_INT.withName("x"),
ValueLayout.JAVA_INT.withName("y"));
static final long X = POINT.byteOffset(PathElement.groupElement("x"));
static final long Y = POINT.byteOffset(PathElement.groupElement("y"));
public static void main(String[] args) throws Throwable {
MemoryLayout ints = MemoryLayout.sequenceLayout(4, ValueLayout.JAVA_INT);
try (Arena arena = Arena.ofConfined()) {
MemorySegment point = arena.allocate(POINT);
point.set(ValueLayout.JAVA_INT, X, 10);
point.set(ValueLayout.JAVA_INT, Y, 20);
MemorySegment array = arena.allocate(ints);
for (int i = 0; i < 4; i++) {
array.set(ValueLayout.JAVA_INT, i * 4L, i + 1);
}
Linker linker = Linker.nativeLinker();
MethodHandle strlen = linker.downcallHandle(
linker.defaultLookup().find("strlen").orElseThrow(),
FunctionDescriptor.of(
ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MemorySegment text = arena.allocateUtf8String("FFM");
System.out.println(point.get(ValueLayout.JAVA_INT, X));
System.out.println((long) strlen.invokeExact(text));
}
}
}| C concept | FFM description |
|---|---|
| `struct { int x; int y; }` | `MemoryLayout.structLayout(...)` |
| `int[4]` | `MemoryLayout.sequenceLayout(4, JAVA_INT)` |
| `size_t strlen(const char*)` | `FunctionDescriptor.of(JAVA_LONG, ADDRESS)` |
Finding a Native Function
SymbolLookup maps a native function name to its address. Linker.nativeLinker().defaultLookup() searches functions supplied by the standard platform libraries. find returns an Optional<MemorySegment>, so orElseThrow() reports a missing symbol immediately.
Describing and Calling a C Signature
FunctionDescriptor records the return layout followed by the argument layouts. A downcall handle is a MethodHandle connected to a native function. The handle's Java argument and return types must match the descriptor exactly.
Exercise
What descriptor models a C function returning int and accepting one pointer?
Show answer
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)