Sub topic 8
Calling C from Java with a downcall handle
A downcall is a call from Java into native code. This chapter assumes you know MethodHandle, the basics of Arena and MemorySegment, and how to read a C signature. It needs JDK 22 or later.
The working model
A downcall needs three pieces:
- The address of the native function, found with a
SymbolLookup. - A
FunctionDescriptorthat describes the C signature with layouts. - A
Linker, which combines the two into aMethodHandle.
Linker.nativeLinker() returns the linker for the current platform. Its defaultLookup() finds symbols in common system libraries, such as the C standard library.
Worked example: strlen
The C signature is size_t strlen(const char *s). On a 64-bit platform, size_t is 64 bits wide, so the return type is JAVA_LONG. The pointer parameter is ADDRESS.
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:
java --enable-native-access=ALL-UNNAMED StrlenDemo.javaReading the example
findreturns anOptional<MemorySegment>. The segment holds the function's address.orElseThrow()fails fast if the symbol does not exist on this platform.FunctionDescriptor.of(returnLayout, argLayouts...)lists the return layout first. UseFunctionDescriptor.ofVoid(...)for functions that return nothing.- The handle's Java type comes from the descriptor.
JAVA_LONGbecomeslong, andADDRESSbecomesMemorySegment. Here the handle has type(MemorySegment)long. - The arena owns the string's memory. The call must finish before the
tryblock closes.
Common errors
Wrong call shape with invokeExact
invokeExact requires the call site's types to match the handle's type exactly. Without the (long) cast, the compiler infers Object as the return type. The call then fails at run time with WrongMethodTypeException. Passing an argument whose static type is not MemorySegment fails the same way. Use invoke if you want automatic conversions, but it is slower.
Descriptor does not match the C signature
The linker cannot check your descriptor against the real function. If you declare JAVA_INT for a size_t return value, you read only half the result. A wrong argument count or type can crash the JVM. Always check the signature in the C header.
Missing native access flag
Linker methods are restricted. Without --enable-native-access, the JVM prints a warning. A later chapter covers how to control this.
Freed memory
If the arena closes before the call, the pointer you pass is no longer valid. A confined arena catches many such mistakes in Java code. Memory that native code keeps and uses later is not checked.
Checked exceptions
invokeExact declares throws Throwable. Your method needs a matching throws clause or a catch block.
Exercise
A handle for int abs(int) was built with FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT). Which call compiles and runs correctly with invokeExact: int r = (int) abs.invokeExact(-5); or long r = (long) abs.invokeExact(-5);?
Show answer
The first one. The handle's type is (int)int, and invokeExact needs the call site to match it exactly. The second call has a long return type, so it throws WrongMethodTypeException.