Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
kvi5hnuCode Sprout team member17 min readOn this page
The previous two articles dealt with the memory half of the FFM API: arenas, segments and layouts. This article covers the other half, calling native functions. A downcall is a call from Java into native code. Making one takes three ingredients:
- the address of the function, found by a
SymbolLookup; - a FunctionDescriptor that lists the layouts of the return value and the parameters;
- the Linker, which combines the two into a
MethodHandlethat you invoke like any other method handle.

The native linker
Linker.nativeLinker() returns the linker for the platform the JVM runs on. It knows the platform's calling convention, the rules for which registers and stack slots hold arguments and results, which differ between, say, Linux on x64, macOS on AArch64 and Windows on x64. This is the work that JNI pushed onto a C compiler. The FFM linker does it at run time and generates efficient code for each downcall handle.
The linker supplies a few other services:
defaultLookup()is a symbol lookup for a set of commonly used libraries.canonicalLayouts()gives the layouts of C types on this platform (see Article 108).downcallHandlecreates a handle that calls native code, andupcallStubcreates a native function pointer that calls Java code (Article 110).
Finding symbols
A SymbolLookup maps a symbol name to an address. There are three ways to get one:
linker.defaultLookup()finds functions in libraries that are always present on the platform. Which libraries these are is platform-specific, but in practice the C standard library is included. On Linux that is libc together with libm and libdl, on macOS it is libSystem, and on Windows it is the universal C runtime plus a few system DLLs. Functions such asstrlen,qsort,mallocandprintfare found this way.SymbolLookup.libraryLookup(nameOrPath, arena)loads a specific library. The argument is aStringlibrary name, which the operating system searches for on its library path (LD_LIBRARY_PATHon Linux, for example), or aPathto the library file. The library stays loaded until the arena closes. WithArena.global()orArena.ofAuto()it stays loaded as long as needed. A library that cannot be found causes anIllegalArgumentException. Because loading a library runs its initialization code,libraryLookupis a restricted method.SymbolLookup.loaderLookup()finds symbols in libraries that the caller's class loader loaded withSystem.loadLibraryorSystem.load, the same libraries a JNI program would use.
Lookups can be combined with or, which tries a second lookup when the first finds nothing:
SymbolLookup lookup = SymbolLookup.libraryLookup("libsqlite3.so.0", arena).or(linker.defaultLookup());
find(name) returns an Optional<MemorySegment>. findOrThrow(name), added in Java 23, returns the segment directly and throws NoSuchElementException when the symbol is missing. A missing library function is usually a deployment problem that the code cannot fix locally, so findOrThrow is normally the right choice. The returned segment has size zero. It stands for the address of the code, not for memory you could read.
System.mapLibraryName("sndfile") turns a base name into the platform's file name: libsndfile.so on Linux, libsndfile.dylib on macOS and sndfile.dll on Windows. Note that Linux distributions often install only the versioned name (libsndfile.so.1) unless the development package is present.
Function descriptors
A FunctionDescriptor describes the C signature in terms of layouts:
// size_t strlen(const char *s)
FunctionDescriptor strlenDesc = FunctionDescriptor.of(JAVA_LONG, ADDRESS);
// void free(void *p)
FunctionDescriptor freeDesc = FunctionDescriptor.ofVoid(ADDRESS);
of takes the return layout first, followed by the parameter layouts. ofVoid is for functions that return nothing. The allowed layouts are:
- Value layouts for numbers and characters. Each layout determines the Java type of that argument or result:
JAVA_INTis passed as anint,JAVA_DOUBLEas adouble, and so on. Mind the C type sizes. A Clongis aJAVA_LONGon Linux and macOS but aJAVA_INTon Windows, so take it fromcanonicalLayouts()when portability matters. Asize_tis aJAVA_LONGon 64-bit platforms. ADDRESSfor every pointer, whatever it points to:char *,int *,SNDFILE *or a function pointer. In Java the argument is aMemorySegment.- Struct and union layouts for aggregates passed or returned by value (not by pointer). The argument is a segment that holds the struct.
The descriptor must match the real C declaration. The linker cannot check it, because a compiled native library carries no type information. A mismatch produces garbage results at best and a JVM crash at worst. This is one of the reasons why creating a downcall handle is a restricted operation.
Downcall handles
MethodHandle strlen = linker.downcallHandle(lookup.findOrThrow("strlen"), FunctionDescriptor.of(JAVA_LONG, ADDRESS));
The handle's type follows from the descriptor: here (MemorySegment)long. There is also a form without the address, downcallHandle(descriptor), whose handle takes the function address as an extra first argument. It is useful when the same signature applies to many function pointers, such as entries in a table of callbacks.
Create handles once and keep them in static final fields. Creating a handle is expensive, but calling a constant handle is fast, because the JIT compiler can inline the transition into native code.
Invoking
There are two ways to call a method handle:
invokeExactrequires the call site to match the handle's type exactly. The compiler derives the call site type from the static argument types and the cast on the result:(long) strlen.invokeExact(segment)has type(MemorySegment)longand matches.(int) strlen.invokeExact(segment)compiles, but it fails at run time withWrongMethodTypeException, and so does passing anintliteral where the descriptor saysJAVA_LONG. Write16L, not16.invokeadapts the arguments and result with the usual conversions (widening, boxing, unboxing, casting) before calling. It is more forgiving, but slower when the types do not match exactly.
Prefer invokeExact with explicit casts. Both methods are declared to throw Throwable, so calling code must handle or declare it.
Passing data to C
Primitive arguments are passed directly. Everything else goes through memory segments:
- Strings.
arena.allocateFrom("text")produces a NUL-terminated UTF-8 C string. - Arrays.
arena.allocateFrom(JAVA_INT, 3, 1, 2)produces a Cintarray. Alternatively, allocate an empty array and let C fill it. - Out parameters. C functions often return extra results through a pointer argument, as in
long long strtoll(const char *s, char **end, int base), which reports where parsing stopped. Allocate a pointer-sized variable witharena.allocate(ADDRESS), pass it, and read the result withget(ADDRESS, 0)after the call. - Structs by pointer. Allocate the struct layout, fill in the members, and pass the segment.
By default, a downcall accepts only native segments. Passing a heap segment, such as one that wraps a Java array, throws IllegalArgumentException. The garbage collector may move Java arrays, so a native function cannot be handed their address.
Return values: pointers and NULL
A function that returns a pointer produces a MemorySegment of size zero at the returned address. The JVM cannot know how large the memory is or how long it stays valid, so it allows no access at all. You make that knowledge explicit:
segment.reinterpret(size)gives the segment a size;reinterpret(size, arena, cleanup)additionally attaches it to an arena and registers an action, such as callingfree, to run when the arena closes.- The return layout
ADDRESS.withTargetLayout(layout)sizes every returned segment automatically. - For a C string of unknown length,
reinterpret(Long.MAX_VALUE).getString(0)reads up to the terminating zero byte.
All of these are restricted: if the size is wrong, Java code can read memory it does not own.
A NULL pointer comes back as a segment whose address() is 0. It is not the same object as MemorySegment.NULL, so a comparison with == is always false. Test with segment.equals(MemorySegment.NULL) or segment.address() == 0. When passing NULL to C, use MemorySegment.NULL.
Returning structs by value
A few C functions return a struct by value, for example div_t div(int, int). The handle for such a function takes an extra first parameter of type SegmentAllocator, which it uses to allocate the result (an Arena is a SegmentAllocator):
var result = (MemorySegment) div.invokeExact((SegmentAllocator) arena, 17, 5);
The cast is needed because invokeExact matches the static type, and the handle's parameter type is SegmentAllocator, not Arena. Article 108 contains the complete example.
Linker options
downcallHandle accepts Linker.Option values:
Linker.Option.critical(allowHeapAccess)marks a function as critical: short, never blocking, and never calling back into Java. The linker can then skip the bookkeeping of a thread transition, which makes very short calls cheaper. Withtrue, such a call may also receive heap segments, because the garbage collector cannot run during the call and so cannot move the array. This lets C read and write a Java array directly, without copying. A critical function that blocks for a long time, however, stalls the garbage collector for all threads.Linker.Option.firstVariadicArg(index)is for variadic functions such asprintf, andLinker.Option.captureCallState(...)saveserrnoor, on Windows,GetLastError()right after the call. Both are covered in the next article.
Enabling native access
The restricted methods include Linker.downcallHandle and upcallStub, SymbolLookup.libraryLookup, MemorySegment.reinterpret and AddressLayout.withTargetLayout. Since JDK 24 (JEP 472), loading native code through JNI is subject to the same rules. When code calls a restricted method without permission, the JVM prints a warning on standard error the first time and continues. Future releases are expected to throw an exception instead.
Permission is granted per module:
--enable-native-access=ALL-UNNAMEDfor code on the class path, or--enable-native-access=com.example.audiofor named modules;Enable-Native-Access: ALL-UNNAMEDin the manifest of an executable JAR, so users need no command-line flag;--illegal-native-access=allow,warn(the default) ordenyfor the behavior when no permission was given.
At compile time, javac -Xlint:restricted warns about calls to restricted methods. Annotate the method with @SuppressWarnings("restricted") after you have checked that the descriptor and sizes are right.
Generating bindings with jextract
Writing layouts and descriptors for a large library by hand is tedious and easy to get wrong. jextract, a tool from the OpenJDK project, distributed separately from the JDK, with prebuilt binaries at jdk.java.net/jextract, reads C header files and generates the Java code:
jextract --output src --target-package org.libsndfile --library sndfile /usr/include/sndfile.h
The main options:
| Option | Meaning |
|---|---|
--output dir | where to write the generated sources |
-t, --target-package | package of the generated classes |
-l, --library | library to load: a name, or :path for a file path |
-I, --include-dir | additional header search directory |
-D, --define-macro | define a preprocessor macro |
--include-function, --include-struct, ... | generate only the listed symbols |
--dump-includes file | list all symbols, to edit into an include list |
For sndfile.h it generates a header class sndfile_h with a static method for every C function, so that calls look like sndfile_h.sf_open(path, SFM_READ(), info). It also generates a class SF_INFO with static accessors (SF_INFO.frames(segment), SF_INFO.channels(segment, 2)), SF_INFO.allocate(arena) and SF_INFO.layout(). Constants from #defines become static methods. Because jextract runs the C compiler front end (libclang) on the header, the padding, type sizes and descriptors are those of the platform where jextract runs. For other platforms, generate the bindings there, or generate only portable parts.
jextract is the practical route for large APIs. Hand-written bindings, as in this article, remain useful for a handful of functions and for understanding what the generated code does.
Reversing a sound file
The following program uses libsndfile, a widely used C library for reading and writing sound files (WAV, FLAC, Ogg and, in recent versions, MP3). It reads all frames of a file as floats, reverses their order, and writes them to a new file in the same format. A frame holds one sample per channel, so frames are swapped as units to keep the left and right channels apart. The swapping happens directly in native memory, with slices and copyFrom.
The four libsndfile functions it uses are:
SNDFILE *sf_open(const char *path, int mode, SF_INFO *info);
sf_count_t sf_readf_float(SNDFILE *file, float *frames, sf_count_t count);
sf_count_t sf_writef_float(SNDFILE *file, const float *frames, sf_count_t count);
int sf_close(SNDFILE *file);
SNDFILE is an opaque type: the program never looks inside it, it only passes the pointer back to the library, so ADDRESS is all it needs. sf_strerror(NULL) describes the most recent error. Install the library with your package manager (libsndfile1 on Debian and Ubuntu, libsndfile on Homebrew) and pass the library's name or path as the third argument if the default name is not found.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
import static java.lang.foreign.ValueLayout.*;
/** Reverses a sound file with libsndfile: java --enable-native-access=ALL-UNNAMED SoundReverser.java in.wav out.wav [library] */
public class SoundReverser {
static final int SFM_READ = 0x10, SFM_WRITE = 0x20; // from sndfile.h
// typedef struct { sf_count_t frames; int samplerate, channels, format, sections, seekable; } SF_INFO;
static final StructLayout SF_INFO = MemoryLayout.structLayout(
JAVA_LONG.withName("frames"), // sf_count_t is a 64-bit integer
JAVA_INT.withName("samplerate"),
JAVA_INT.withName("channels"),
JAVA_INT.withName("format"),
JAVA_INT.withName("sections"),
JAVA_INT.withName("seekable"),
MemoryLayout.paddingLayout(4)); // sizeof(SF_INFO) is 32
static final VarHandle FRAMES = SF_INFO.varHandle(groupElement("frames"));
static final VarHandle CHANNELS = SF_INFO.varHandle(groupElement("channels"));
static final VarHandle SAMPLERATE = SF_INFO.varHandle(groupElement("samplerate"));
final MethodHandle sfOpen, sfClose, sfReadfFloat, sfWritefFloat, sfStrerror;
@SuppressWarnings("restricted")
SoundReverser(SymbolLookup lib) {
Linker linker = Linker.nativeLinker();
// SNDFILE *sf_open(const char *path, int mode, SF_INFO *info)
sfOpen = linker.downcallHandle(lib.findOrThrow("sf_open"), FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT, ADDRESS));
// int sf_close(SNDFILE *file)
sfClose = linker.downcallHandle(lib.findOrThrow("sf_close"), FunctionDescriptor.of(JAVA_INT, ADDRESS));
// sf_count_t sf_readf_float(SNDFILE *file, float *frames, sf_count_t count), and the matching writer
sfReadfFloat = linker.downcallHandle(lib.findOrThrow("sf_readf_float"),
FunctionDescriptor.of(JAVA_LONG, ADDRESS, ADDRESS, JAVA_LONG));
sfWritefFloat = linker.downcallHandle(lib.findOrThrow("sf_writef_float"),
FunctionDescriptor.of(JAVA_LONG, ADDRESS, ADDRESS, JAVA_LONG));
// const char *sf_strerror(SNDFILE *file): the returned string is sized by the target layout
sfStrerror = linker.downcallHandle(lib.findOrThrow("sf_strerror"),
FunctionDescriptor.of(ADDRESS.withTargetLayout(MemoryLayout.sequenceLayout(1024, JAVA_BYTE)), ADDRESS));
}
MemorySegment open(Arena arena, String path, int mode, MemorySegment info) throws Throwable {
var file = (MemorySegment) sfOpen.invokeExact(arena.allocateFrom(path), mode, info);
if (file.equals(MemorySegment.NULL)) { // never compare with ==
var message = (MemorySegment) sfStrerror.invokeExact(MemorySegment.NULL);
throw new IllegalStateException(path + ": " + message.getString(0));
}
return file;
}
void reverse(String input, String output) throws Throwable {
try (Arena arena = Arena.ofConfined()) {
MemorySegment info = arena.allocate(SF_INFO);
MemorySegment in = open(arena, input, SFM_READ, info);
long frames = (long) FRAMES.get(info, 0L);
int channels = (int) CHANNELS.get(info, 0L);
MemorySegment samples = arena.allocate(JAVA_FLOAT, frames * channels);
long read = (long) sfReadfFloat.invokeExact(in, samples, frames);
int closed = (int) sfClose.invokeExact(in);
if (read != frames || closed != 0) throw new IllegalStateException("read " + read + " of " + frames + " frames");
// swap whole frames in native memory: frame f trades places with frame frames - 1 - f
long frameBytes = channels * JAVA_FLOAT.byteSize();
MemorySegment temp = arena.allocate(frameBytes);
for (long f = 0; f < frames / 2; f++) {
MemorySegment a = samples.asSlice(f * frameBytes, frameBytes);
MemorySegment b = samples.asSlice((frames - 1 - f) * frameBytes, frameBytes);
temp.copyFrom(a);
a.copyFrom(b);
b.copyFrom(temp);
}
MemorySegment out = open(arena, output, SFM_WRITE, info); // same format, rate and channels
long written = (long) sfWritefFloat.invokeExact(out, samples, frames);
int error = (int) sfClose.invokeExact(out);
if (written != frames || error != 0) throw new IllegalStateException("wrote " + written + " of " + frames + " frames");
System.out.printf("Reversed %d frames, %d channel(s), %d Hz: %s -> %s%n",
frames, channels, (int) SAMPLERATE.get(info, 0L), input, output);
}
}
@SuppressWarnings("restricted") // libraryLookup is restricted too
public static void main(String[] args) throws Throwable {
if (args.length < 2) {
System.out.println("Usage: java --enable-native-access=ALL-UNNAMED SoundReverser.java input output [library]");
return;
}
// a bare name such as libsndfile.so.1 is found on the system library path; a path is loaded directly
String library = args.length > 2 ? args[2] : System.mapLibraryName("sndfile");
try (Arena libraryArena = Arena.ofConfined()) { // the library is unloaded when this arena closes
new SoundReverser(SymbolLookup.libraryLookup(library, libraryArena)).reverse(args[0], args[1]);
}
}
}
Some details are worth noting:
- The
SF_INFOlayout ends with 4 bytes of padding.sf_openwrites all 32 bytes of the struct, so a 28-byte layout would let C write past the end of the segment. - The constants
SFM_READandSFM_WRITEcome from the header file. They are compile-time values in C and do not exist in the compiled library, so a binding has to repeat them (jextract generates them). - When opening for writing,
sf_openreads the format, sample rate and channel count from the sameSF_INFO, so the output has the input's format. - The whole file is held in native memory at once. For long recordings, read and write in blocks of, say, 64K frames.
sf_strerrorreturns a pointer to a C string inside the library. The target layout gives the segment a generous fixed size, andgetStringstops at the first zero byte.
Running java --enable-native-access=ALL-UNNAMED SoundReverser.java speech.wav reversed.wav prints a line such as Reversed 88200 frames, 2 channel(s), 44100 Hz: speech.wav -> reversed.wav.
The program
The demo makes downcalls into the C standard library, so it runs on Linux, macOS and Windows without installing anything. Because it calls the restricted downcallHandle and reinterpret, the JVM prints a four-line warning on standard error unless it runs with --enable-native-access=ALL-UNNAMED. The output below shows standard output only.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.nio.charset.StandardCharsets;
import java.util.NoSuchElementException;
import static java.lang.foreign.ValueLayout.*;
public class Solution {
static final Linker LINKER = Linker.nativeLinker();
static final SymbolLookup LIBC = LINKER.defaultLookup();
// size_t strlen(const char *s)
static final MethodHandle STRLEN = downcall("strlen", FunctionDescriptor.of(JAVA_LONG, ADDRESS));
// int toupper(int c)
static final MethodHandle TOUPPER = downcall("toupper", FunctionDescriptor.of(JAVA_INT, JAVA_INT));
// long long strtoll(const char *s, char **end, int base)
static final MethodHandle STRTOLL = downcall("strtoll", FunctionDescriptor.of(JAVA_LONG, ADDRESS, ADDRESS, JAVA_INT));
// char *getenv(const char *name)
static final MethodHandle GETENV = downcall("getenv", FunctionDescriptor.of(ADDRESS, ADDRESS));
// void *malloc(size_t size) and void free(void *p)
static final MethodHandle MALLOC = downcall("malloc", FunctionDescriptor.of(ADDRESS, JAVA_LONG));
static final MethodHandle FREE = downcall("free", FunctionDescriptor.ofVoid(ADDRESS));
// void *memset(void *p, int value, size_t count)
static final MethodHandle MEMSET = downcall("memset", FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT, JAVA_LONG));
@SuppressWarnings("restricted")
static MethodHandle downcall(String name, FunctionDescriptor descriptor, Linker.Option... options) {
return LINKER.downcallHandle(LIBC.findOrThrow(name), descriptor, options);
}
public static void main(String[] args) throws Throwable {
lookups();
simpleCalls();
outParameters();
pointersAndNull();
nativeMemory();
criticalCalls();
}
static void lookups() {
System.out.println("== Symbol lookup ==");
System.out.println("find(\"strlen\") present: " + LIBC.find("strlen").isPresent()
+ "; find(\"no_such_function\") present: " + LIBC.find("no_such_function").isPresent());
try {
LIBC.findOrThrow("no_such_function");
} catch (NoSuchElementException e) {
System.out.println("findOrThrow: NoSuchElementException");
}
MemorySegment address = LIBC.findOrThrow("strlen");
System.out.println("a symbol is a zero-length segment: size " + address.byteSize()
+ ", address non-zero " + (address.address() != 0));
System.out.println("descriptor " + FunctionDescriptor.of(JAVA_LONG, ADDRESS) + " -> handle type " + STRLEN.type());
}
static void simpleCalls() throws Throwable {
System.out.println();
System.out.println("== Simple downcalls ==");
try (Arena arena = Arena.ofConfined()) {
MemorySegment text = arena.allocateFrom("Panama");
long length = (long) STRLEN.invokeExact(text); // exact: MemorySegment -> long
System.out.println("strlen(\"Panama\") = " + length);
Object boxed = STRLEN.invoke(text); // invoke adapts the types, here boxing
System.out.println("invoke returns a " + boxed.getClass().getSimpleName() + ": " + boxed);
try {
int wrong = (int) STRLEN.invokeExact(text); // the call site type must match exactly
System.out.println(wrong);
} catch (java.lang.invoke.WrongMethodTypeException e) {
System.out.println("(int) invokeExact: WrongMethodTypeException");
}
}
var sb = new StringBuilder();
for (char c : "native".toCharArray()) sb.append((char) (int) TOUPPER.invokeExact((int) c));
System.out.println("toupper on each char: " + sb);
}
static void outParameters() throws Throwable {
System.out.println();
System.out.println("== Out parameters: strtoll(s, &end, base) ==");
try (Arena arena = Arena.ofConfined()) {
MemorySegment input = arena.allocateFrom("0x7fff rest");
MemorySegment end = arena.allocate(ADDRESS); // a char* variable for C to fill in
long value = (long) STRTOLL.invokeExact(input, end, 16);
MemorySegment endPointer = end.get(ADDRESS, 0);
long consumed = endPointer.address() - input.address();
System.out.println("value " + value + ", C consumed " + consumed + " chars, the rest is \""
+ input.getString(consumed) + "\"");
}
}
static void pointersAndNull() throws Throwable {
System.out.println();
System.out.println("== Returned pointers ==");
try (Arena arena = Arena.ofConfined()) {
var missing = (MemorySegment) GETENV.invokeExact(arena.allocateFrom("FFM_DEMO_SURELY_UNSET"));
System.out.println("getenv of an unset variable: equals(MemorySegment.NULL) " + missing.equals(MemorySegment.NULL)
+ ", == NULL " + (missing == MemorySegment.NULL) + ", address " + missing.address());
var path = (MemorySegment) GETENV.invokeExact(arena.allocateFrom("PATH"));
if (!path.equals(MemorySegment.NULL)) {
System.out.println("getenv(\"PATH\") returns a segment of size " + path.byteSize());
try {
path.get(JAVA_BYTE, 0);
} catch (IndexOutOfBoundsException e) {
System.out.println("reading it directly: IndexOutOfBoundsException");
}
@SuppressWarnings("restricted")
MemorySegment sized = path.reinterpret(Long.MAX_VALUE); // a C string: size unknown, read up to the 0 byte
System.out.println("after reinterpret: PATH matches System.getenv: "
+ sized.getString(0).equals(System.getenv("PATH")));
}
}
}
@SuppressWarnings("restricted")
static void nativeMemory() throws Throwable {
System.out.println();
System.out.println("== malloc, memset and free ==");
var raw = (MemorySegment) MALLOC.invokeExact(16L);
if (raw.equals(MemorySegment.NULL)) throw new OutOfMemoryError("malloc");
try (Arena arena = Arena.ofConfined()) {
// give the block a size, and let the arena call free when it closes
MemorySegment block = raw.reinterpret(16, arena, p -> {
try {
FREE.invokeExact(p);
System.out.println("cleanup action: free called");
} catch (Throwable t) {
throw new AssertionError(t);
}
});
var result = (MemorySegment) MEMSET.invokeExact(block, 0x2a, 16L);
System.out.println("memset returned the same address: " + (result.address() == block.address())
+ "; bytes " + java.util.Arrays.toString(block.toArray(JAVA_BYTE)));
}
}
static void criticalCalls() throws Throwable {
System.out.println();
System.out.println("== Heap segments and critical calls ==");
byte[] bytes = "heap text\0".getBytes(StandardCharsets.US_ASCII);
MemorySegment heap = MemorySegment.ofArray(bytes);
try {
long n = (long) STRLEN.invokeExact(heap);
System.out.println(n);
} catch (IllegalArgumentException e) {
System.out.println("heap segment to a normal downcall: IllegalArgumentException");
}
MethodHandle criticalStrlen = downcall("strlen", FunctionDescriptor.of(JAVA_LONG, ADDRESS),
Linker.Option.critical(true)); // allow heap access, no copying
System.out.println("critical(true) strlen on a byte[]: " + (long) criticalStrlen.invokeExact(heap));
}
}
== Symbol lookup ==
find("strlen") present: true; find("no_such_function") present: false
findOrThrow: NoSuchElementException
a symbol is a zero-length segment: size 0, address non-zero true
descriptor (a8)j8 -> handle type (MemorySegment)long
== Simple downcalls ==
strlen("Panama") = 6
invoke returns a Long: 6
(int) invokeExact: WrongMethodTypeException
toupper on each char: NATIVE
== Out parameters: strtoll(s, &end, base) ==
value 32767, C consumed 6 chars, the rest is " rest"
== Returned pointers ==
getenv of an unset variable: equals(MemorySegment.NULL) true, == NULL false, address 0
getenv("PATH") returns a segment of size 0
reading it directly: IndexOutOfBoundsException
after reinterpret: PATH matches System.getenv: true
== malloc, memset and free ==
memset returned the same address: true; bytes [42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
cleanup action: free called
== Heap segments and critical calls ==
heap segment to a normal downcall: IllegalArgumentException
critical(true) strlen on a byte[]: 9
Points to notice:
findreturned an emptyOptionalfor the missing symbol, andfindOrThrowthrew. A found symbol is a zero-length segment that holds the function's address.- The descriptor
(a8)j8became a handle of type(MemorySegment)long. invokeboxed the result into aLong; castinginvokeExacttointfailed because the types must match exactly.strtollwrote the end pointer into thechar*variable; subtracting the addresses gave the number of characters it parsed.- The NULL returned by
getenvwasequalstoMemorySegment.NULLbut not==, and thePATHvalue could be read only afterreinterpret. - The cleanup action registered with
reinterpretcalledfreewhen the arena closed. - A heap segment was rejected by the normal
strlenhandle but accepted by the critical one.
Common questions
How do I find the right FunctionDescriptor for a C function?
Map each C type by size: int to JAVA_INT, long to JAVA_LONG on Linux and macOS but JAVA_INT on Windows, size_t to JAVA_LONG on 64-bit platforms, pointers to ADDRESS, double to JAVA_DOUBLE. Linker.nativeLinker().canonicalLayouts() gives the platform's mapping for names like "long" and "size_t".
Why do I get WrongMethodTypeException from invokeExact?
The call site's types must match the handle exactly, including the return type cast: (long) strlen.invokeExact(segment), not int and not Object. Use invoke to allow conversions, at a small cost.
How do I check whether a returned pointer is NULL?
Compare with MemorySegment.NULL.equals(result) or result.address() == 0. Don't use ==, since a new segment object is returned each time.
How do I read data from a pointer returned by C?
The returned segment has size 0. Call result.reinterpret(size) (a restricted method) with the size you know from the API documentation, optionally with an arena and a cleanup action that frees the memory.
Are downcalls slow?
They cost a few nanoseconds more than a Java call, similar to JNI or faster. For very short functions that never block, Linker.Option.critical(false) removes more overhead.
API reference
| Class / method | Purpose |
|---|---|
Linker.nativeLinker(), defaultLookup(), canonicalLayouts() | The platform linker. |
downcallHandle(address, descriptor, options...), downcallHandle(descriptor, options...) | Creating downcall handles (restricted). |
SymbolLookup.libraryLookup(name or path, arena), loaderLookup(), or(lookup) | Library and loader lookups. |
find(name), findOrThrow(name) | Finding a symbol's address. |
FunctionDescriptor.of(result, params...), ofVoid(params...), returnLayout(), argumentLayouts() | Describing a C signature. |
MethodHandle.invokeExact, invoke, type() | Calling the handle. |
MemorySegment.NULL, equals, address() | NULL pointers and addresses. |
reinterpret(size), reinterpret(size, arena, cleanup), AddressLayout.withTargetLayout | Sizing returned pointers (restricted). |
Linker.Option.critical(allowHeapAccess), firstVariadicArg, captureCallState | Linker options. |
System.mapLibraryName(name) | Platform-specific library file names. |
--enable-native-access, Enable-Native-Access, --illegal-native-access | Granting native access. |
jextract | Generating bindings from C headers. |
Summary
- A downcall needs a function address from a
SymbolLookup(default, library or loader lookup), aFunctionDescriptorthat mirrors the C signature, andLinker.downcallHandle, which produces aMethodHandle. - The linker cannot verify descriptors; a wrong one can crash the JVM. Use platform-correct layouts,
ADDRESSfor all pointers, and struct layouts for structs passed by value. - Call handles with
invokeExactand exact casts. Keep handles instatic finalfields. - Arguments are primitives or native segments; strings and arrays are allocated in arenas, and out parameters are pointer-sized segments. Heap segments need a critical function with heap access allowed.
- Returned pointers are zero-length segments. Size them with
reinterpretor a target layout, and test for NULL withequals(MemorySegment.NULL), never==. - Restricted methods warn unless native access is enabled with
--enable-native-accessor theEnable-Native-Accessmanifest attribute. - jextract generates layouts and wrapper methods from C headers for larger libraries.
Practice Questions
1. Write the downcall handle for the C function double pow(double x, double y), and show the call.
MethodHandle pow = linker.downcallHandle(linker.defaultLookup().findOrThrow("pow"), FunctionDescriptor.of(JAVA_DOUBLE, JAVA_DOUBLE, JAVA_DOUBLE)); The call is double r = (double) pow.invokeExact(2.0, 10.0);, which gives 1024.0. The arguments must be double values; writing pow.invokeExact(2, 10) passes ints and throws WrongMethodTypeException. On Linux, pow lives in libm, which the default lookup includes.
2. A program checks if (result == MemorySegment.NULL) after a native call that returned NULL. Why does the check fail, and what is correct?
The linker wraps every returned pointer in a new MemorySegment object, including a null pointer, so the result is a different object from the constant MemorySegment.NULL and == compares references. Segments implement equals by comparing the address (and the kind of memory), so result.equals(MemorySegment.NULL) is true for a NULL return. result.address() == 0 works as well.
3. What happens if the descriptor for strlen says JAVA_INT for the result instead of JAVA_LONG?
The linker trusts the descriptor. On common 64-bit platforms the result comes back in a 64-bit register, and the handle reads only its lower 32 bits, so short strings appear to work and the bug goes unnoticed until a string is longer than 2 GB. Other mismatches, such as a wrong number of arguments or a value passed where a pointer is expected, can crash the JVM. Descriptors must be derived from the C declaration and the platform's type sizes, ideally by jextract.
4. When should a downcall be marked critical, and what does critical(true) add?
For functions that run for a very short time, never block and never call back into Java, such as strlen or a small math routine, especially when called in a tight loop. The linker can then skip the thread state transition and its safepoint checks, which saves time. critical(true) additionally allows heap segments as arguments, so native code can work directly on a Java array without copying it into native memory, because the garbage collector cannot move the array during a critical call. Long-running or blocking functions must not be critical, because they would delay garbage collection for the whole JVM.
5. What does jextract generate, and what are its limitations?
From C header files it generates Java source: a header class with a static method for each function (and accessors for its address, descriptor and handle), a class for each struct or union with a layout and getters and setters, methods for constants and macros, and support for variadic functions and function pointers. It uses libclang, so the layouts reflect the platform it runs on: bindings for a C long or a struct with platform-dependent padding must be generated on each target platform. It cannot translate macros that are not simple constants, it does not understand ownership or lifetime rules from documentation, and it is installed separately from the JDK.
Previous: FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Related reading
- FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
- Foreign Function and Memory API: Arenas and Memory Segments
- Native Methods with JNI: Calling C Code from Java
- Printing in Java: Print Jobs, Multipage Printing and Print Services
- Raster Images in Java: ImageIO, BufferedImage Pixels and Image Filters

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Native Methods with JNI: Calling C Code from Java
The Java Native Interface: declaring native methods, generating headers with javac -h, JNI function naming and type mapping, strings and modified UTF-8, arrays, calling Java from C, exceptions, references, building and loading libraries, native access restrictions, and why the FFM API replaces JNI.
Discussion
Sign in to ask a question or share what you learned.