Sub topic 11
Callbacks: letting C call Java
This chapter assumes you can already create a downcall handle and use an Arena. If not, read the chapters on downcall handles and arenas first.
Why callbacks exist
Some C functions take a function pointer and call it later. The standard library's qsort is the classic case. You pass it an array and a comparison function, and it calls your function many times while sorting. To use such an API from Java, you need a C-callable function pointer that runs a Java method. The FFM API calls this an upcall stub.
A downcall goes from Java into C. An upcall goes from C back into Java.
Building an upcall stub
Creating a stub takes three things:
- A
MethodHandlefor the Java method to run. - A
FunctionDescriptorthat describes the C signature the caller expects. - An
Arenathat controls how long the stub stays valid.
Linker.upcallStub combines them and returns a MemorySegment. That segment holds the address of the native entry point. You pass it wherever C expects a function pointer.
The C comparator has the signature int (*cmp)(const void *, const void *). Its two parameters are pointers to ints, so the descriptor uses an ADDRESS layout with a target layout of JAVA_INT. That tells the linker to give your Java method segments that are exactly 4 bytes long. Without a target layout, the segments have zero length and any read throws an exception.
A complete example
This program sorts a native int array with C qsort. It targets Java 22. On Java 23 and later, replace allocateArray with allocateFrom. Run it with --enable-native-access=ALL-UNNAMED.
import java.lang.foreign.AddressLayout;
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;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
public class QsortDemo {
static int compare(MemorySegment a, MemorySegment b) {
return Integer.compare(a.get(ValueLayout.JAVA_INT, 0), b.get(ValueLayout.JAVA_INT, 0));
}
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
AddressLayout intPtr = ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT);
// void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *));
// size_t is modeled as JAVA_LONG, which is correct on 64-bit platforms.
MethodHandle qsort = linker.downcallHandle(
linker.defaultLookup().find("qsort").orElseThrow(),
FunctionDescriptor.ofVoid(ValueLayout.ADDRESS, ValueLayout.JAVA_LONG,
ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MethodHandle cmp = MethodHandles.lookup().findStatic(QsortDemo.class, "compare",
MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
FunctionDescriptor cmpDesc = FunctionDescriptor.of(ValueLayout.JAVA_INT, intPtr, intPtr);
try (Arena arena = Arena.ofConfined()) {
MemorySegment stub = linker.upcallStub(cmp, cmpDesc, arena);
MemorySegment array = arena.allocateArray(ValueLayout.JAVA_INT, 5, 3, 9, 1, 7);
qsort.invokeExact(array, 5L, 4L, stub);
System.out.println(Arrays.toString(array.toArray(ValueLayout.JAVA_INT))); // [1, 3, 5, 7, 9]
}
}
}The MethodType of the handle must match the descriptor. Here the descriptor has two address parameters and an int result, so the Java method takes two MemorySegment arguments and returns int. A mismatch throws IllegalArgumentException when you create the stub.
Lifetime of the stub
The arena you pass to upcallStub owns the stub. When the arena closes, the stub's native code is freed. If C still holds the pointer and calls it afterwards, the process can crash.
Common errors
- Uncaught exceptions. If the Java method throws, the JVM cannot propagate the exception through C frames. It terminates the process. Catch exceptions inside the method and return an error value instead.
- Zero-length segments. Pointer parameters without a target layout have length zero. Add
withTargetLayoutor reinterpret the segment. - Wrong C types. Declaring a
longparameter where C usesintreads garbage, because the layouts decide how arguments are passed. - Slow callbacks. Each upcall crosses the native boundary. Keep the Java method short.
Exercise
In the qsort example, why does the comparator descriptor use ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT) instead of plain ValueLayout.ADDRESS?
Show answer
A plain ADDRESS parameter reaches Java as a zero-length MemorySegment, so reading an int from it throws an exception. The target layout makes each segment 4 bytes long, which is the size of the int it points to.