Sub topic 9
Working with C strings
This chapter assumes you can already bind a C function with a downcall handle and manage an Arena. It uses the Java 22 method names. Java 23 and later renamed them, as noted below.
What a C string is
A C string is a run of bytes ended by a zero byte, and a char * points at the first byte. A Java String is an object on the heap with its own length, so it cannot be passed to native code directly. You copy it into native memory, pass the address, and copy results back out.
Passing a string to C
Arena.allocateUtf8String(String) encodes the text as UTF-8, appends the terminating zero byte, and returns a MemorySegment. The descriptor models a char * parameter as ValueLayout.ADDRESS. The strlen example from the earlier chapter uses exactly this pattern.
The segment lives as long as its arena. Choose an arena that outlives the call. A confined arena in a try-with-resources block is the usual choice.
Reading a string that C returns
A function such as getenv returns a char *. The returned pointer has no size information, so the runtime gives you a segment of length zero. Reading it directly throws IndexOutOfBoundsException. You must widen it with reinterpret, which tells the runtime how many bytes you are willing to trust.
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 GetenvDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle getenv = linker.downcallHandle(
linker.defaultLookup().find("getenv").orElseThrow(),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment name = arena.allocateUtf8String("PATH");
MemorySegment result = (MemorySegment) getenv.invokeExact(name);
if (result.address() == 0) {
System.out.println("PATH is not set");
} else {
String value = result.reinterpret(Long.MAX_VALUE).getUtf8String(0);
System.out.println(value);
}
}
}
}getUtf8String(0) scans from offset 0 until it finds a zero byte, then decodes the bytes as UTF-8. Passing Long.MAX_VALUE as the size is safe only because the string is zero-terminated, so the scan stops at the terminator. If the function documents a real length, use that length instead.
Run it with --enable-native-access=ALL-UNNAMED, because reinterpret is a restricted method.
Checking for NULL
A C function can return NULL. A NULL pointer arrives as a segment whose address is 0. Check address() == 0 before you call reinterpret. Skipping this check means reading from address 0 and crashing the JVM.
Who owns the returned memory
The getenv result belongs to the C runtime. You must not free it, and you must copy it into a Java String if you need it later. Other functions, such as strdup, return memory that the caller must release with free. Read the C documentation for each function. The arena does not manage memory it did not allocate.
Renamed methods in later releases
| Task | Java 22 | Java 23 and later |
|---|---|---|
| Java string to native | `arena.allocateUtf8String(s)` | `arena.allocateFrom(s)` |
| Native to Java string | `segment.getUtf8String(offset)` | `segment.getString(offset)` |
Exercise
A downcall returns a char * as a MemorySegment, and calling getUtf8String(0) on it throws IndexOutOfBoundsException. What is the cause, and how do you fix it?
Show answer
Native pointers returned from a downcall are zero-length segments, because the runtime does not know how large the pointed-to memory is. Check for a null address first. Then call reinterpret(Long.MAX_VALUE) (or the real size) on the segment and read the string from the result. This needs native access to be enabled.
Exercise
Why does the GetenvDemo code allocate the name inside an arena but never free the result of getenv?
Show answer
The arena allocated the name, so closing the arena frees it. The getenv result is owned by the C runtime, so Java must not free it. Java should copy it into a String if the value is needed later.