Sub topic 8
Calling C from Java with a downcall handle
A downcall handle is a MethodHandle that, when invoked, calls a C function. This chapter shows how to build one, how to call it correctly, and which errors to expect when the Java and C sides disagree.
This chapter assumes you know:
- Java fundamentals and
try-with-resources. - The basics of
MethodHandle, includinginvokeExact. - C function signatures.
- How to allocate a
MemorySegmentfrom anArena. - That
ValueLayoutconstants describe C types.
You need JDK 22 or later. The examples use the Java 22 method names. In Java 23 and later, allocateUtf8String is called allocateFrom.
The three ingredients
A downcall is a call from Java into native code. Building a handle takes three pieces:
- The address of the function. A
SymbolLookupfinds it by name and returns aMemorySegmentthat points at the function's code. - The shape of the function. A
FunctionDescriptorlists the return layout and the parameter layouts. - The linker.
Linker.nativeLinker()combines the address and the descriptor into aMethodHandlethat follows the platform's calling convention.
A first call: strlen
This program calls the C function size_t strlen(const char *s).
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class StrlenDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle strlen = linker.downcallHandle(
linker.defaultLookup().find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment str = arena.allocateUtf8String("Hello, FFM");
long length = (long) strlen.invokeExact(str);
System.out.println(length); // 10
}
}
}Run it with native access enabled for your class path code:
java --enable-native-access=ALL-UNNAMED StrlenDemo.javaWithout the flag, Java 22 still runs the program but prints a warning, because downcallHandle is a restricted method. A later chapter covers that mechanism in detail.
Each step does the following:
linker.defaultLookup()returns aSymbolLookupover the common system libraries, such as the C standard library.findreturns anOptional<MemorySegment>, which is empty if the symbol does not exist.orElseThrow()turns that into aNoSuchElementExceptionat startup instead of a failure later.FunctionDescriptor.of(returnLayout, paramLayouts...)describessize_t strlen(const char *). Heresize_tis modeled asJAVA_LONG, which is correct on 64-bit platforms. Thechar *isADDRESS.downcallHandlereturns aMethodHandlewhose Java type is derived from the descriptor, in this case(MemorySegment)long.
How descriptors become Java types
The method type of the handle comes entirely from the descriptor. The table shows the usual mappings.
| C type | Layout | Java type in the handle |
|---|---|---|
| `int` | `JAVA_INT` | `int` |
| `long long`, `int64_t` | `JAVA_LONG` | `long` |
| `size_t` (64-bit) | `JAVA_LONG` | `long` |
| `double` | `JAVA_DOUBLE` | `double` |
| `float` | `JAVA_FLOAT` | `float` |
| `char *`, `void *`, any pointer | `ADDRESS` | `MemorySegment` |
| `struct` passed or returned by value | a `StructLayout` | `MemorySegment` |
| `void` return | `FunctionDescriptor.ofVoid(...)` | `void` |
Choose the layout from the C type's real size on the target platform, not from its name. A C long is 64 bits on Linux and macOS but 32 bits on Windows, so it maps to JAVA_LONG on the first two and JAVA_INT on Windows. The linker cannot detect a wrong size. It uses your descriptor as written and passes the wrong register or stack contents.
Wrapping a handle in a normal method
Handles are best created once and stored in a static final field. The JIT compiler can then treat the handle as a constant and inline the call. Wrap the invokeExact call in an ordinary method so the rest of your code never sees Throwable.
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class AbsDemo {
private static final Linker LINKER = Linker.nativeLinker();
// int abs(int j);
private static final MethodHandle ABS = LINKER.downcallHandle(
LINKER.defaultLookup().find("abs").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
public static int abs(int value) {
try {
return (int) ABS.invokeExact(value);
} catch (Throwable t) {
throw new AssertionError("native abs failed", t);
}
}
public static void main(String[] args) {
System.out.println(abs(-42)); // 42
}
}Catching Throwable is required because invokeExact is declared to throw it. A downcall cannot throw a C exception, since C has none. Throwables here come from the Java side: a wrong call shape, a closed segment, or an upcall that threw.
Why invokeExact is strict
invokeExact requires the static types at the call site to match the handle's type exactly, including the return type. The cast (long) in the first example is part of that match.
Two common mistakes:
- Calling
strlen.invokeExact(str)without the cast and assigning to along. The compiler treats the expression's return type asObject, so the call fails at run time withWrongMethodTypeException. - Passing an
intliteral to alongparameter. The call-site type is(int), not(long), so it also fails. Write5L.
invoke (without Exact) adapts types for you, for example widening an int to a long. It is slower and hides mistakes, so prefer invokeExact in bindings you write by hand.
Looking up functions in other libraries
defaultLookup() covers only standard system libraries. To call something else, load the library into a lookup with a lifetime you control.
import java.lang.foreign.Arena;
import java.lang.foreign.SymbolLookup;
public class LibLookupDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
SymbolLookup lib = SymbolLookup.libraryLookup("libm.so.6", arena);
System.out.println(lib.find("cos").isPresent());
}
}
}The library name is platform specific. On Linux it is libm.so.6, on macOS libm.dylib, and on Windows the C math functions already live in the default lookup. The library stays loaded until the arena closes. Using a symbol address after that point is undefined behavior, because the arena no longer guards it. SymbolLookup.loaderLookup() finds symbols in libraries loaded by the current class loader through System.loadLibrary.
Pointers, nulls and returned addresses
Several rules apply when a handle takes or returns an ADDRESS.
- Pass
MemorySegment.NULLfor a C null pointer. A JavanullthrowsNullPointerException. - Heap segments are rejected. A segment backed by a Java array, such as
MemorySegment.ofArray(new int[4]), cannot be passed to a downcall. The call throwsIllegalArgumentException, because the garbage collector may move the array. Copy the data into a native segment first. - Closed segments are rejected. If the segment's arena is closed, the call throws
IllegalStateException. - Returned pointers have zero length. The runtime does not know how much memory a returned
char *points to, so the segment's size is 0. Reading from it throwsIndexOutOfBoundsException. You can attach a target layout to the descriptor, such asValueLayout.ADDRESS.withTargetLayout(...), when the size is known. Otherwise usereinterpret(size), which is itself a restricted method and removes the bounds protection.
Structs by value and the allocator parameter
If the C function returns a struct by value, the handle needs somewhere to put the result. The linker adds a SegmentAllocator as the first parameter of the handle. The returned MemorySegment is allocated from it. Passing a struct by value takes a MemorySegment argument of the matching size, like any pointer.
The same prefix idea applies to the other form of the factory method. linker.downcallHandle(FunctionDescriptor) takes no symbol, and the resulting handle has a MemorySegment address as its first parameter. That is useful for function pointers that you receive at run time, such as a callback field in a struct.
Failure modes
| Symptom | Usual cause |
|---|---|
| `NoSuchElementException` from `orElseThrow` | Symbol name wrong, or library not in the lookup |
| `WrongMethodTypeException` | Call-site types or cast differ from the descriptor |
| `IllegalArgumentException` | Heap segment passed, or descriptor with an invalid layout |
| `IllegalStateException` | Segment's arena already closed, or called from the wrong thread for a confined arena |
| JVM crash or garbage values | Descriptor does not match the real C signature |
The last row is the hard one. The API checks that Java types are consistent with your descriptor. It cannot check that your descriptor is consistent with the C function. A wrong layout silently reads the wrong register, and the process may crash.
Exercise
A handle is built with FunctionDescriptor.of(ValueLayout.JAVAINT, ValueLayout.JAVAINT), and you call it with long r = (long) h.invokeExact(5);. What happens, and what is the fix?
Show answer
The call throws WrongMethodTypeException. invokeExact requires the call-site type to equal the handle type (int)int, but the site has type (int)long because of the cast. Fix it by casting to int: int r = (int) h.invokeExact(5);. Widen to long afterwards if needed.
Exercise
You need to call double sqrt(double x) from the default lookup. Write the FunctionDescriptor, and explain why a long argument such as 4L would fail.
Show answer
FunctionDescriptor.of(ValueLayout.JAVADOUBLE, ValueLayout.JAVADOUBLE). The handle type is (double)double. With invokeExact, passing a long gives the call-site type (long)double, which does not match, so WrongMethodTypeException is thrown. Pass 4.0 and cast the result to double.