1 +#
Java 26 Foreign Function & Memory API — distilled 4 +Oracle Java SE 26 core guide + `java.lang.foreign` API docs.
8 +FFM (`java.lang.foreign`) lets Java code:
10 +- call native/foreign functions without JNI glue;
11 +- pass Java code as native function pointers;
12 +- allocate/access off-heap memory safely with bounds/lifetime checks;
13 +- model native structs/unions/arrays/pointers via layouts.
15 +FFM is stable since Java 22.
16 +Java 26 docs describe same core model with JDK 26 API pages.
21 +| ------------------------------ | ----------------------------------------------------------------------------------------- |
22 +| `Arena` | Owns lifetime of native segments. Allocate via `allocate`, `allocateFrom`; close to free. |
23 +| `MemorySegment` | Bounds-checked view over heap/native/mapped memory. Has address, byte size, scope. |
24 +| `SegmentAllocator` | Allocation interface implemented by `Arena`; helpers copy Java data to native memory. |
25 +| `MemoryLayout` | Describes size/alignment/field structure; creates var handles. |
26 +| `ValueLayout` | Primitive layouts (`JAVA_INT`, `JAVA_LONG`, `ADDRESS`, unaligned variants, byte order). |
27 +| `AddressLayout` | Pointer layout. Optional target layout enables dereference sizing. |
28 +| `SequenceLayout` | Array layout. |
29 +| `StructLayout` / `UnionLayout` | C `struct` / `union` layout. Add explicit padding for ABI. |
30 +| `FunctionDescriptor` | Native function signature: return layout + arg layouts. |
31 +| `Linker` | ABI-specific bridge; creates downcall handles and upcall stubs. |
32 +| `SymbolLookup` | Resolves native symbol names to function addresses. |
33 +| `Linker.Option` | `firstVariadicArg`, `captureCallState("errno")`, critical/capture options. |
35 +##
Arenas and lifetimes 37 +Use arenas to allocate native/off-heap segments.
40 +try (
Arena arena
= Arena.ofConfined()) {
41 + MemorySegment buf
= arena.allocate(
1024,
8);
42 + buf.set(
JAVA_INT,
0,
42);
48 +- `Arena.ofConfined()` — deterministic lifetime, owner-thread only; default
50 +- `Arena.ofShared()` — deterministic lifetime, accessible/closable by multiple
51 + threads; close is safe/atomic.
52 +- `Arena.ofAuto()` — GC-managed lifetime; any thread; cannot close manually.
53 +- `Arena.global()` — never freed; any thread; cannot close manually.
55 +Closed arena → segment access throws `IllegalStateException`.
56 +Out-of-bounds → `IndexOutOfBoundsException`.
57 +Wrong thread for confined arena → access/close fails.
64 + `MemorySegment.ofArray(...)`, backed by Java array;
68 + from `FileChannel.map(..., Arena)`.
73 +int x
= segment.get(
JAVA_INT,
0);
74 +segment.set(
JAVA_INT,
4,
123);
75 +int y
= segment.getAtIndex(
JAVA_INT,
3);
76 +segment.setAtIndex(
JAVA_INT,
3,
456);
82 +MemorySegment c
= arena.allocateFrom(
"hello");
83 +String s
= c.getString(
0);
89 +MemorySegment nativeInts
= arena.allocateFrom(
JAVA_INT,
new int[] {
3,
1,
2});
90 +int[] copy
= nativeInts.toArray(
JAVA_INT);
96 +MemorySegment slice
= segment.asSlice(
16,
8);
99 +Parallel/disjoint work:
100 +use `Arena.ofShared()` and `segment.elements(layout)` when multiple threads need
103 +##
Alignment and endianness 105 +Layouts carry byte size, byte alignment, and byte order.
106 +Segment access validates alignment.
108 +- Native segment address + offset must satisfy layout alignment.
109 +- Heap segment max alignment depends on backing array type.
110 +- For packed/unaligned data use `JAVA_INT_UNALIGNED`, etc.
111 +- For non-native byte order use `layout.withOrder(ByteOrder.BIG_ENDIAN)`.
114 +int be
= segment.get(
JAVA_INT.withOrder(
ByteOrder.
BIG_ENDIAN),
0);
119 +Always treat C mapping as ABI/platform-dependent.
123 +Map<
String,
MemoryLayout> canon
= Linker.nativeLinker().canonicalLayouts();
124 +MemoryLayout size_t
= canon.get(
"size_t");
127 +All native linkers provide canonical layouts for:
128 +`bool`, `char`, `short`, `int`, `long`, `long long`, `float`, `double`,
129 +`size_t`, `wchar_t`, `void*`.
131 +Typical Linux/x64 mappings:
133 +| C type | Java FFM layout | Java carrier |
134 +| --------------------------------- | ------------------------------------------- | --------------- |
135 +| `bool` | `JAVA_BOOLEAN` | `boolean` |
136 +| `char`, `unsigned char` | `JAVA_BYTE` | `byte` |
137 +| `short`, `unsigned short` | `JAVA_SHORT` | `short` |
138 +| `int`, `unsigned int` | `JAVA_INT` | `int` |
139 +| `long`, `unsigned long` | `JAVA_LONG` | `long` |
140 +| `long long`, `unsigned long long` | `JAVA_LONG` | `long` |
141 +| `float` | `JAVA_FLOAT` | `float` |
142 +| `double` | `JAVA_DOUBLE` | `double` |
143 +| `size_t` | `JAVA_LONG` on 64-bit, `JAVA_INT` on 32-bit | `long`/`int` |
144 +| `T*`, function pointer | `ADDRESS` | `MemorySegment` |
145 +| `struct` | `structLayout(...)` | `MemorySegment` |
146 +| `union` | `unionLayout(...)` | `MemorySegment` |
148 +Unsigned types use same-size signed carriers; interpret with Java unsigned
149 +helpers (`Integer.toUnsignedLong`, `Long.compareUnsigned`, masks) as needed.
153 +Downcall = Java → native function.
158 +static final Linker LINKER = Linker.nativeLinker();
159 +static final SymbolLookup LOOKUP = LINKER.defaultLookup();
161 +static final MethodHandle strlen
= LINKER.downcallHandle(
162 + LOOKUP.findOrThrow(
"strlen"),
163 + FunctionDescriptor.of(
JAVA_LONG,
ADDRESS)
166 +static long strlen(
String s) throws
Throwable {
167 + try (
Arena arena
= Arena.ofConfined()) {
168 + return (
long) strlen.invokeExact(arena.allocateFrom(s));
175 +- `FunctionDescriptor.of(returnLayout, argLayouts...)`.
176 +- `FunctionDescriptor.ofVoid(argLayouts...)` for `void` return.
177 +- `MethodHandle.invokeExact` requires exact Java carriers and return cast.
178 +- `ADDRESS` args/returns are `MemorySegment`.
179 +- Descriptor must match actual native signature.
180 + Linker cannot verify; mismatch can crash JVM.
185 +SymbolLookup std
= Linker.nativeLinker().defaultLookup();
187 +SymbolLookup lib
= SymbolLookup.libraryLookup(
"libc.so.6", arena);
190 +`libraryLookup` is restricted because library loading may execute native code.
194 +Upcall = native → Java through function pointer.
199 +void qsort(
void *base,
size_t nmemb,
size_t size,
200 + int (
*compar)(
const void *,
const void *));
206 +static int compareInts(
MemorySegment a,
MemorySegment b) {
207 + return Integer.compare(a.get(
JAVA_INT,
0), b.get(
JAVA_INT,
0));
210 +static final Linker LINKER = Linker.nativeLinker();
211 +static final MethodHandle QSORT = LINKER.downcallHandle(
212 + LINKER.defaultLookup().findOrThrow(
"qsort"),
213 + FunctionDescriptor.ofVoid(
ADDRESS,
JAVA_LONG,
JAVA_LONG,
ADDRESS)
216 +static void sort(
int[] input) throws
Throwable {
217 + FunctionDescriptor cmpDesc
= FunctionDescriptor.of(
219 + ADDRESS.withTargetLayout(
JAVA_INT),
220 + ADDRESS.withTargetLayout(
JAVA_INT)
222 + MethodHandle cmp
= MethodHandles.lookup().findStatic(
225 + cmpDesc.toMethodType()
228 + try (
Arena arena
= Arena.ofConfined()) {
229 + MemorySegment cmpPtr
= LINKER.upcallStub(cmp, cmpDesc, arena);
230 + MemorySegment arr
= arena.allocateFrom(
JAVA_INT, input);
231 + QSORT.invokeExact(arr, (
long) input.length,
JAVA_INT.byteSize(), cmpPtr);
232 + int[] sorted
= arr.toArray(
JAVA_INT);
237 +Upcall stub lifetime must outlive native use.
238 +If native stores callback pointer, do not use a short-lived confined arena
239 +unless pointer is invalidated before close.
241 +##
Pointers returned by native functions and pointer out-parameters 243 +For C output parameters like `T** out`, allocate one pointer-sized slot, pass it
244 +to native code, then read the actual returned pointer:
247 +MemorySegment out
= arena.allocate(
ADDRESS);
248 +int rc
= some_open(..., out);
249 +MemorySegment handle
= out.get(
ADDRESS,
0);
252 +Do not pass the slot (`out`) to later functions expecting `T*`; pass `handle`.
253 +This distinction is critical for APIs such as `sqlite3_open(..., sqlite3**)` and
254 +`sqlite3_prepare_v2(..., sqlite3_stmt**)`.
256 +Native pointer returns/read pointers usually become zero-length
261 +- scope is global/always alive;
262 +- direct access throws out-of-bounds.
264 +Attach bounds/lifetime before dereference.
266 +Example `malloc/free` wrapper:
269 +static final Linker LINKER = Linker.nativeLinker();
270 +static final SymbolLookup C = LINKER.defaultLookup();
272 +static final MethodHandle malloc
= LINKER.downcallHandle(
273 + C.findOrThrow(
"malloc"),
274 + FunctionDescriptor.of(
ADDRESS,
JAVA_LONG)
276 +static final MethodHandle free
= LINKER.downcallHandle(
277 + C.findOrThrow(
"free"),
278 + FunctionDescriptor.ofVoid(
ADDRESS)
281 +static MemorySegment mallocSegment(
long bytes,
Arena arena) throws
Throwable {
282 + MemorySegment raw
= (
MemorySegment) malloc.invokeExact(bytes);
283 + return raw.reinterpret(bytes, arena, s
-> {
285 + free.invokeExact(s);
286 + }
catch (
Throwable t) {
287 + throw new RuntimeException(t);
293 +If bounds statically known for a pointer field/arg:
296 +AddressLayout int4Ptr
= ADDRESS.withTargetLayout(sequenceLayout(
4,
JAVA_INT));
297 +MemorySegment p
= segment.get(int4Ptr, offset);
300 +`reinterpret` and `AddressLayout.withTargetLayout` are restricted because wrong
301 +bounds/lifetime can corrupt memory/crash JVM.
303 +##
Structs, arrays, layouts 308 +struct Point {
int x;
int y; } pts[
10];
311 +Java layout + var handles:
314 +static final SequenceLayout POINTS = sequenceLayout(
10,
316 + JAVA_INT.withName(
"x"),
317 + JAVA_INT.withName(
"y")
321 +static final VarHandle X = POINTS.varHandle(sequenceElement(), groupElement(
"x"));
322 +static final VarHandle Y = POINTS.varHandle(sequenceElement(), groupElement(
"y"));
324 +try (
Arena arena
= Arena.ofConfined()) {
325 + MemorySegment pts
= arena.allocate(
POINTS);
326 + X.set(pts,
0L,
3L,
10);
327 + int x
= (
int)
X.get(pts,
0L,
3L);
331 +For C padding/alignment:
335 +StructLayout EXAMPLE = structLayout(
336 + JAVA_INT.withName(
"x"),
338 + JAVA_LONG.withName(
"y")
342 +Native linker function descriptors require well-formed layouts.
343 +Group layouts must include appropriate padding and satisfy natural
344 +alignment/size rules.
345 +Packed structs may be rejected by some linkers.
347 +##
Variadic functions 349 +FFM links specialized non-variadic forms.
350 +Use `Linker.Option.firstVariadicArg(index)`.
355 +int printf(
const char *format,
...);
361 +MethodHandle printf
= LINKER.downcallHandle(
362 + LINKER.defaultLookup().findOrThrow(
"printf"),
363 + FunctionDescriptor.of(
JAVA_INT,
ADDRESS,
JAVA_INT,
JAVA_INT,
JAVA_INT),
364 + Linker.
Option.firstVariadicArg(
1)
367 +try (
Arena arena
= Arena.ofConfined()) {
368 + int rc
= (
int) printf.invokeExact(
369 + arena.allocateFrom(
"%d plus %d equals %d\n"),
2,
2,
4 374 +C default promotions apply conceptually; FFM does not auto-promote.
375 +Use promoted layouts for variadic args (`float` → `double`, small ints → `int`).
376 +Linker rejects non-promoted variadic layouts depending on platform.
380 +Use `Linker.Option.captureCallState("errno")` on downcall handle and pass
381 +captured-state segment as leading argument to the method handle.
384 +static final Linker.
Option CAP_ERRNO = Linker.
Option.captureCallState(
"errno");
385 +static final StructLayout CAPTURED = Linker.
Option.captureStateLayout();
386 +static final VarHandle ERRNO = CAPTURED.varHandle(groupElement(
"errno"));
388 +static final MethodHandle fopen
= LINKER.downcallHandle(
389 + C.findOrThrow(
"fopen"),
390 + FunctionDescriptor.of(
ADDRESS,
ADDRESS,
ADDRESS),
394 +try (
Arena arena
= Arena.ofConfined()) {
395 + MemorySegment state
= arena.allocate(
CAPTURED);
396 + MemorySegment file
= (
MemorySegment) fopen.invokeExact(
398 + arena.allocateFrom(
"missing.txt"),
399 + arena.allocateFrom(
"r")
401 + if (file.address()
== 0) {
402 + int errno
= (
int)
ERRNO.get(state,
0L);
407 +Use `strerror(errno)` to convert to message if needed; returned string pointer
408 +likely needs `reinterpret(Long.MAX_VALUE).getString(0)` or known bound.
409 +This is restricted/unsafe; prefer bounded APIs if available.
411 +##
Restricted methods and native access 413 +Restricted FFM-related operations:
415 +- `Linker.downcallHandle(...)` — signature mismatch is unsafe.
416 +- `Linker.upcallStub(...)` — function pointer type/lifetime mismatch is unsafe.
417 +- `SymbolLookup.libraryLookup(...)` — loading libraries can execute native code.
418 +- `MemorySegment.reinterpret(...)` — changes bounds/lifetime alias.
419 +- `AddressLayout.withTargetLayout(...)` — enables pointer dereference sizing.
420 +- `ModuleLayer.Controller.enableNativeAccess(...)` — propagates native
423 +Enable native access at run time; FFM itself is final in Java 26, so FFM-only
424 +code does not need `--enable-preview`.
427 +javac --release 26 Main.java
428 +java --enable-native-access
=ALL-UNNAMED Main
429 +java --enable-native-access
=my.module Main
432 +More selective is better:
433 +put FFM code on module path and enable only that module.
435 +Control illegal native access:
438 +java --illegal-native-access
=allow
|warn
|deny ...
441 +JDK 24+ default is `warn`; future default expected `deny`.
445 +Use `jextract` when binding nontrivial headers.
448 +<https://jdk.java.net/jextract/>
\ 450 +<https://github.com/openjdk/jextract>
456 + -l :/absolute/path/to/libfoo.so \
458 + -I /path/to/include \
459 + -t com.example.foo \
462 +javac -sourcepath gensrc Main.java
463 +java -cp gensrc:. --enable-native-access
=ALL-UNNAMED Main
466 +Generated bindings handle many descriptors, layouts, and upcall helpers.
467 +Still review ownership/lifetime/error conventions.
471 +- Missing `--enable-native-access` → warning or `IllegalCallerException`
472 + depending config/JDK.
473 +- `invokeExact` args not exact carriers (`int` vs `long`, missing return cast) →
474 + `WrongMethodTypeException`.
475 +- Using Linux/x64 layout assumptions on Windows/x64 (`long` mismatch).
476 +- Mapping `size_t`/`strlen` to `JAVA_INT` on Linux/x64; use `JAVA_LONG` or
477 + canonical `size_t` layout.
478 +- Guessing C macro constants such as `sysconf` names; use `jextract` or
479 + generated constants.
480 +- Accessing arena segment after close → `IllegalStateException`.
481 +- Passing confined-arena segment to another thread → failure.
482 +- Dereferencing zero-length pointer without sizing →
483 + `IndexOutOfBoundsException`.
484 +- Confusing pointer out-parameter slots (`T**`) with returned handles (`T*`) →
485 + native `SQLITE_MISUSE`, crashes, or corrupted state.
486 +- Wrong `FunctionDescriptor` → unspecified behavior/JVM crash.
487 +- Forgetting C struct padding/alignment → corrupted fields/native call failure.
488 +- Upcall stub arena closes while native code still stores callback pointer →
489 + dangling function pointer.
490 +- Native code stores pointer to arena buffer after arena close → dangling
492 +- Treating unsigned values as signed without conversion.
493 +- Assuming Java memory model guarantees for native memory; normal JMM guarantees
494 + do not apply to off-heap native segments.
495 +- Using `Arena.global()` or `ofAuto()` where deterministic cleanup required.
499 +- Small C function, simple signature → hand-code downcall.
500 +- Many functions/structs/macros/header churn → `jextract`.
501 +- Native returns allocated pointer → wrap with `reinterpret(size, arena,
502 + cleanup)` and matching free.
503 +- Native writes into caller buffer → allocate in arena, pass segment, read after
505 +- Native stores callback/buffer past call → allocate with lifetime covering
506 + native use; define explicit close/unregister.
507 +- Cross-thread native access → shared arena or copy data to heap.