Sub topic 3
Working with C Strings and Callbacks
Assume Java 22 or later, basic MethodHandle knowledge, and familiarity with C pointers, function signatures, and null-terminated strings.
C strings
A C string is a sequence of bytes ending with a zero byte. Java strings use UTF-16 characters, so native calls need an encoding conversion. Arena.allocateUtf8String allocates a null-terminated UTF-8 string whose lifetime belongs to the arena.
import java.lang.foreign.*;
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 text = arena.allocateUtf8String("Hello");
long length = (long) strlen.invokeExact(text);
System.out.println(length);
}
}
}Restricted methods
Methods that can access native resources are restricted. Run this unnamed-module program with:
java --enable-native-access=ALL-UNNAMED StrlenDemoWithout this option, the JDK can issue a warning. Named modules should declare native access in their module configuration.
Callbacks from C
An upcall lets native code call Java. Find a static Java method with MethodHandles.lookup(), describe its C-compatible signature with FunctionDescriptor, and pass the resulting MemorySegment from linker.upcallStub to C. Keep the arena open while native code might call the callback.
Reading `errno`
For a native function that reports errors through errno, create a downcall handle with Linker.Option.captureCallState("errno"). Supply storage for the captured state, call the function, then read the named errno field immediately. Do not assume that a later native or Java operation preserves it.
Variadic functions
Functions such as printf have a variable number of arguments. Use Linker.Option.firstVariadicArg(index) and provide exact layouts for every argument. Variadic ABI rules differ between platforms, so a fixed-arity C wrapper is usually safer.
Generating bindings with `jextract`
jextract reads a C header and generates Java classes containing layouts, symbol lookups, and method handles. This avoids repeating declarations manually.
jextract --output src --target-package example.native native_api.hUse a jextract version compatible with the JDK and target platform.
Pitfalls
- An arena closing invalidates all its segments.
- Match native sizes. C
longandsize_tare platform-dependent; do not blindly map them to Javalong. - A pointer layout describes an address, not the pointed-to data. Add a target layout when dereferencing.
- Confined arenas must be accessed by their owning thread. Use a shared arena only when its synchronization and lifetime are appropriate.
Exercise
Why must the arena remain open while C can invoke a Java callback?
Show answer
The upcall stub and any memory it uses are arena-owned. Closing the arena invalidates them, so a later native call cannot safely use the callback.