Lesson · Foreign Function & Memory API
Linker and SymbolLookup: calling C from Java
12 min readLinker & SymbolLookup
A native call is a claim about a foreign ABI that nothing on either side can verify for you. Linker and SymbolLookup turn that claim into a MethodHandle: find the address, describe the C signature, invoke, and keep every borrowed byte alive for the duration.
The linker speaks the platform ABI
Java's calling convention is not C's. A native function expects arguments in particular registers or stack slots, expects certain types promoted in certain ways, and returns values the same way. Linker.nativeLinker() is the object that knows those rules for the platform the JVM is running on: the OS plus processor combination, not the Java version.
One linker mediates both directions. A downcall is Java calling a C function; an upcall is C calling back into Java. Both start from the same two inputs: the address of the foreign function, modelled as a MemorySegment, and a FunctionDescriptor that states the C signature.
The API does not hide the ABI, it formalizes it. Type sizes, padding and calling conventions become explicit values in Java code, which is the price of not shipping a compiler for every target.
Two directions, one description. Downcall and upcall share the symbol address and the FunctionDescriptor; the difference is only which side starts the call.
Finding a symbol
Before anything can be linked, the function's address has to be found. SymbolLookup is that step, and it answers with an Optional: an empty result is the normal way to say that this name does not resolve in this place.
| Lookup | Covers | Notes |
|---|---|---|
linker.defaultLookup() | libraries commonly loaded with the process (libc and libm on Linux) | the cheapest first stop; the exact set is platform-dependent |
SymbolLookup.loaderLookup() | libraries loaded through System.load or System.loadLibrary | stays current as more libraries load; does not see libraries opened by libraryLookup |
SymbolLookup.libraryLookup(name, arena) (or a Path) | one specific library, loaded on demand | restricted operation; the arena owns the load, so closing it unloads |
- find(name) returns Optional<MemorySegment>. The segment is zero-length: it models an address, it is not a region you can read. Empty means the name did not resolve here, and it is not an exception.
- Names differ per platform. libc on Linux may really be libc.so.6, Windows resolves through LoadLibrary, and a symbol can carry a version suffix. When a lookup comes back empty, the first question is which spelling exists on this machine.
- Chain lookups with or(...). The first lookup that finds the symbol wins, which is how a library search order is expressed.
- The method is find in JDK 22, renamed from lookup when the API became final; older tutorials and preview-era code use the old name.
An empty Optional is information, not a failure. Retry the platform's spelling before concluding that the library is missing.
The descriptor maps C types to layouts
A FunctionDescriptor lists the return layout and the parameter layouts, in order. Every entry is a MemoryLayout, usually a ValueLayout, and the C to layout mapping is the platform ABI's: the same C type can map to two different layouts on two platforms.
| C type | Layout | Java carrier |
|---|---|---|
| bool | ValueLayout.JAVA_BOOLEAN | boolean |
| int, unsigned int | ValueLayout.JAVA_INT | int |
| long, unsigned long | JAVA_LONG on Linux/x64, JAVA_INT on Windows/x64 | long or int |
| size_t | JAVA_LONG on 64-bit platforms, JAVA_INT on 32-bit | long or int |
| char*, void*, any pointer | ValueLayout.ADDRESS | MemorySegment |
| struct, union | structLayout(...) or unionLayout(...), padding written down | MemorySegment |
- Pointers are addresses, arguments are segments. An ADDRESS parameter is filled with a MemorySegment, and an ADDRESS return comes back as a zero-length segment with global scope.
- Structs need explicit padding, exactly as in the arena lesson: the linker requires each member to sit at an offset compatible with its alignment, which is what C did when it laid the struct out.
- A target layout adds bounds.
ADDRESS.withTargetLayout(layout)describes the pointee, so the address that comes back has a size instead of being zero-length. - Sequences cannot be argument or return types. A native linker rejects a descriptor whose layouts include a sequence layout; composite values cross as structs or pointers.
Wrong descriptor, no error. The javadoc is blunt: creating a downcall handle is intrinsically unsafe, the linker cannot validate linkage requests, and the result of an invalid request is unspecified, up to a JVM crash. Only the header can tell you what is true.
Structure · two rails, one description
an address plus a FunctionDescriptor, in both directions
Arguments cross as memory segments allocated in an arena; the return crosses as the descriptor says, and an ADDRESS return is a zero-length segment with global scope until you attach bounds.
The stub runs on the thread that entered the native call. Its lifetime is the arena, so the arena has to outlive every use C makes of the pointer.
Java calls C: downcall handles
A downcall handle is an ordinary MethodHandle whose invocation drops into native code. The address comes from a lookup, the signature from the descriptor, and then it is called like any other handle.
The worked example is the smallest useful foreign function there is: size_t strlen(const char *s).
Linker linker = Linker.nativeLinker();then a symbol:linker.defaultLookup().find("strlen").orElseThrow().- Describe the signature:
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS). size_t is 64-bit here, so it is JAVA_LONG. - Create the handle:
MethodHandle handle = linker.downcallHandle(symbol, descriptor);. Creating it is a restricted operation. - Allocate the argument in an arena with
arena.allocateFrom("AlgoLab"), invoke the handle, and read the returned long: 7. invokeExactrequires the static argument and return types to match the handle exactly;invokeis the relaxed sibling that applies the usual method handle conversions.
- Struct returns take an allocator. When the return layout is a group layout, the handle gains a leading
SegmentAllocatorparameter, and the linker allocates the returned struct into it. - Pointer returns are zero-length and global. The runtime cannot know the size or the lifetime of a region a foreign function allocated.
segment.reinterpret(size, arena, cleanup)attaches both, or read the pointer through a target layout when the shape is known at compile time. - Captured state is written to a segment.
Linker.Option.captureCallState("errno")adds a capture segment parameter to the handle; you pass in an allocated segment and read the saved values back through the capture layout. Windows exposes GetLastError and WSAGetLastError instead of errno.
The arena owns the arguments; you own the copies. Anything the native call borrows has to stay alive until it returns, and anything you keep afterwards has to be a Java value or a segment with a longer-lived arena.
Two rails · downcall, then upcall
Linker.nativeLinker() is the bridge to the platform ABI. Calling conventions and type sizes come from the OS plus processor combination under this JVM, never from the Java language.
The same linker serves both rails; the arrow on the station that is waiting is the only thing that changes direction.
C calls Java: upcall stubs
The reverse direction wraps a Java method handle into a native function pointer. Linker.upcallStub(target, descriptor, arena) returns a zero-length segment whose address C can call, and whose lifetime is the arena's scope.
- Take the C signature of the callback:
int (*compar)(const void *, const void *)becomes a descriptor of JAVA_INT with two ADDRESS parameters, each with a target layout of JAVA_INT so the comparator can read the elements. - Convert it to a method type and look up a matching static Java method, then turn it into a pointer:
linker.upcallStub(target, descriptor, arena). - Pass the stub to the downcall handle as an ordinary ADDRESS argument:
qsort(array, count, 4L, stub). - qsort calls back once per comparison while the downcall is running, and the stub stays valid because the arena is still open. It is retired when the arena closes.
- The descriptor describes the C signature of the pointer, and
descriptor.toMethodType()gives the exact Java type the target method handle must have. - The stub runs on the calling thread. When C invokes the pointer inside a downcall, the Java method runs in that same call, on the thread that entered native code.
- The target must not throw. An exception crossing an upcall boundary terminates the JVM abruptly, so wrap the target with
MethodHandles.catchExceptionor catch inside it. - Keep the stub alive while C holds it. The arena is all that keeps that address valid; closing it while a library still stores the pointer is a crash, not an exception.
An upcall does not extend anyone's lifetime. The arena you choose for the stub must outlive every use C makes of the pointer, including uses that happen long after the call that registered it.
Native access is opt in
Linking native code can compromise the integrity of the whole process, so the operations that do it are restricted methods: they run only when the application has enabled native access for the calling module.
The restricted FFM set is small and specific: libraryLookup, downcallHandle, upcallStub, reinterpret, and the target-layout operations that can synthesize bounds.
- Enable it at startup:
--enable-native-access=ALL-UNNAMEDfor code on the class path, or a comma-separated list of module names. An executable jar can carryEnable-Native-Access: ALL-UNNAMEDin its manifest instead. - JDK 22 to 23: a restricted call from a module without native access warns on first use, at most once per module. One pre-24 quirk: if some module had native access enabled but the caller did not, the call threw IllegalCallerException instead of warning.
- JDK 24 (JEP 472) aligned FFM with JNI. Illegal native access now warns by default under
--illegal-native-access=warn,denyis the documented default for a future release, and JNI's load and loadLibrary joined the restricted set. - The grant belongs to a module. Code can ask with
Module::isNativeAccessEnabled, and modular applications can grant the option per module rather than globally.
Treat the flag as part of the deployment contract. A library that links native code has to tell its users which option to pass, because the application developer is the one who decides.
jextract, and the failure modes that remain
Hand-written descriptors are the exception in serious projects. jextract reads a C header and generates Java sources with the layouts, lookups and downcall handles already assembled, so the type mapping, including struct padding, is done once, by a tool, in generated code you can inspect.
| Failure | What it looks like | First move |
|---|---|---|
| Empty Optional | a name you expected does not resolve | check the platform's library and symbol spelling, including version suffixes |
| Wrong descriptor | garbage results or a crash, with no link error at all | walk each entry against the header, starting with size_t width and struct padding |
| Missing native access | a warning on first use in JDK 22 to 24, an exception once deny is the default | pass --enable-native-access for the calling module |
- Confirm the symbol resolves at all, with the platform's own spelling of the library.
- Walk the descriptor entry by entry against the header: return type first, then each parameter, checking size_t and long for width and structs for padding.
- Check the byte order only if the C side works with a non-native order; native order is the default for every layout constant.
- Watch for restricted-method warnings at startup, and pass the enable-native-access option if they appear.
- Reduce to the smallest call that misbehaves, then compare it against the header again. When a native call returns nonsense, the descriptor is the first suspect.
The linker is not the bug. When a native call misbehaves, the odds are on the claim you made about the C signature, not on the machinery dispatching it.
The descriptor that looks right
size_t is 8 bytes on every 64-bit platform you are likely to ship, but it is a distinct C type, and on a 32-bit platform it maps to JAVA_INT. Write it as JAVA_INT out of habit and nothing complains: the handle links, the call runs, and the value that comes back is garbage because the upper half of the register was never part of the result. C cannot correct you and the linker promised it would not try. The habit that prevents this is mechanical: open the header while writing the descriptor, and generate it with jextract whenever the header is available.
Interview angles
How do you build a downcall from Java to a C function?+
Find the address with a SymbolLookup, describe the signature with FunctionDescriptor.of(returnLayout, paramLayouts...), create the handle with linker.downcallHandle(symbol, descriptor), allocate any arguments in an arena, and invoke it. Both downcallHandle and the library lookup are restricted methods, so native access has to be enabled.
Where do symbols come from?+
The linker's defaultLookup covers libraries commonly loaded with the process, loaderLookup covers libraries loaded through System.load, and libraryLookup opens a specific library under an arena that unloads it on close. find returns an Optional, so a missing symbol is empty rather than an exception.
Common misconception: That a missing symbol throws. It does not: the Optional is empty, and the first debugging step is the platform's spelling of the library and symbol name.
What can go wrong with a wrong FunctionDescriptor?+
Nothing at link time: the linker cannot validate a linkage request, so an invalid descriptor produces unspecified behaviour, from garbage values to a JVM crash. The classic is mapping size_t to JAVA_INT, which silently truncates the result on a 64-bit platform.
Follow-up: Which is why bindings come from jextract in practice, and hand-written descriptors are reviewed against the header.
How do you pass a Java method to C as a callback?+
Wrap the method handle with linker.upcallStub(target, descriptor, arena). The result is a zero-length segment C can call, valid for as long as the arena lives, so the arena has to outlive every use C makes of the pointer. The target must not throw: an exception crossing the boundary terminates the JVM.