Sub topic 7
Describing a C signature with FunctionDescriptor
This chapter assumes you can read a C function prototype, you know what a MethodHandle is, and you have a JDK 22 or later installation. You should also have seen Linker and SymbolLookup in the earlier chapters.
A symbol lookup gives you the address of a native function. That address says nothing about the function's arguments or return value. A FunctionDescriptor supplies that missing information.
What a FunctionDescriptor is
A FunctionDescriptor is an immutable object. It holds one optional return layout and an ordered list of argument layouts. It is the Java description of a C prototype such as long strlen(const char *s).
The linker uses the descriptor for three jobs:
- It chooses the calling convention: which registers or stack slots carry each argument, and where the result comes back.
- It derives the Java
MethodTypeof the resultingMethodHandle. - It checks that each layout is something the linker can pass by value on the current platform.
The linker cannot inspect native code. If your descriptor disagrees with the real C signature, nothing detects it. Section "Descriptor mismatches" covers what happens then.
Building a descriptor
There are two factory methods.
FunctionDescriptor.of(returnLayout, argLayouts...)describes a function that returns a value.FunctionDescriptor.ofVoid(argLayouts...)describes a function that returns nothing.
The return layout comes first, which matches C's reading order. The C prototype int abs(int j) becomes:
FunctionDescriptor abs = FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT);A prototype with no parameters uses an empty argument list: FunctionDescriptor.of(ValueLayout.JAVA_INT) describes int rand(void).
Because descriptors are immutable, the "modifier" methods return a new descriptor:
| Method | Effect |
|---|---|
| `appendArgumentLayouts(layouts...)` | Adds layouts at the end of the argument list |
| `insertArgumentLayouts(index, layouts...)` | Adds layouts at a position |
| `changeReturnLayout(layout)` | Replaces the return layout |
| `dropReturnLayout()` | Turns the descriptor into a void one |
These are useful when several functions share most of a signature. They also let you derive a descriptor for a variant function from a base one.
You can inspect a descriptor with returnLayout(), which returns an Optional<MemoryLayout>, and argumentLayouts(), which returns a List<MemoryLayout>.
Choosing the right layout for each C type
Each C type maps to a layout, and each layout has a Java carrier type. The carrier is the Java type that appears in the MethodType.
| C type | Layout | Java carrier |
|---|---|---|
| `char`, `signed char` | `JAVA_BYTE` | `byte` |
| `short` | `JAVA_SHORT` | `short` |
| `int` | `JAVA_INT` | `int` |
| `long long` | `JAVA_LONG` | `long` |
| `float` | `JAVA_FLOAT` | `float` |
| `double` | `JAVA_DOUBLE` | `double` |
| `bool` (C99 `_Bool`) | `JAVA_BOOLEAN` | `boolean` |
| any pointer | `ADDRESS` | `MemorySegment` |
| struct passed or returned by value | a `StructLayout` | `MemorySegment` |
Two C types do not map the same way on every platform.
longis 64 bits on Linux and macOS (LP64) and 32 bits on Windows. UseJAVA_LONGon the first group andJAVA_INTon Windows.size_tis the width of a pointer. On 64-bit platforms it isJAVA_LONG. The qsort example in the topic uses this mapping.
Hard-coding either choice produces code that works on your machine and fails on another. The linker publishes the platform's real mapping through Linker.nativeLinker().canonicalLayouts(). This returns a map from C type names such as "int", "long" and "size_t" to layouts.
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
public class CanonicalDemo {
public static void main(String[] args) {
Linker linker = Linker.nativeLinker();
MemoryLayout sizeT = linker.canonicalLayouts().get("size_t");
MemoryLayout cLong = linker.canonicalLayouts().get("long");
System.out.println("size_t: " + sizeT.byteSize() + " bytes");
System.out.println("long: " + cLong.byteSize() + " bytes");
}
}On 64-bit Linux this prints 8 for both. On 64-bit Windows it prints 8 for size_t and 4 for long.
Pointers and target layouts
Every pointer argument uses ValueLayout.ADDRESS, whatever it points to. The layout carries no information about the pointee unless you add it with withTargetLayout, as in ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT).
A target layout matters when native code returns a pointer, or hands one to an upcall. Without it, the MemorySegment you receive has length zero, and every access fails. With the target layout, the segment gets that layout's size. For pointers you only pass into native code, plain ADDRESS is enough.
Looking at the derived method type
toMethodType() shows what Java type the handle will have. Printing it is a quick way to check your descriptor.
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.ValueLayout;
public class DescriptorDemo {
public static void main(String[] args) {
// size_t strlen(const char *s), with size_t modeled as long
FunctionDescriptor strlen =
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS);
System.out.println(strlen.toMethodType()); // (MemorySegment)long
System.out.println(strlen.returnLayout().isPresent()); // true
// void free(void *ptr)
FunctionDescriptor free = FunctionDescriptor.ofVoid(ValueLayout.ADDRESS);
System.out.println(free.toMethodType()); // (MemorySegment)void
System.out.println(free.returnLayout().isPresent()); // false
// Derive a descriptor with one more argument
FunctionDescriptor wider = strlen.appendArgumentLayouts(ValueLayout.JAVA_INT);
System.out.println(wider.toMethodType()); // (MemorySegment,int)long
}
}Passing a descriptor to the linker
Linker.downcallHandle(MemorySegment symbol, FunctionDescriptor descriptor, Linker.Option... options) takes the symbol address and the descriptor. The handle's type is the descriptor's method type. This holds for the exact-invocation rule too:
invokeExact requires the call site's static types to match the handle type exactly. Mismatches fail at run time with WrongMethodTypeException.
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.WrongMethodTypeException;
public class AbsDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
// int abs(int j)
MethodHandle abs = linker.downcallHandle(
linker.defaultLookup().find("abs").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
System.out.println(abs.type()); // (int)int
int result = (int) abs.invokeExact(-5);
System.out.println(result); // 5
try {
long wrong = (long) abs.invokeExact(-5L); // (long)long, not (int)int
} catch (WrongMethodTypeException e) {
System.out.println("Call site does not match the descriptor");
}
}
}Use invoke instead of invokeExact if you want Java to adapt types for you, for example widening int to long. The adaptation only converts Java values to the handle's type. It never checks the handle against the real C function.
Structs by value
C functions can take or return a struct by value, not through a pointer. Describe this with a StructLayout in the descriptor, not with ADDRESS. The standard library function div_t div(int numer, int denom) returns a struct of two int fields:
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SegmentAllocator;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class DivDemo {
static final StructLayout DIV_T = MemoryLayout.structLayout(
ValueLayout.JAVA_INT.withName("quot"),
ValueLayout.JAVA_INT.withName("rem"));
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle div = linker.downcallHandle(
linker.defaultLookup().find("div").orElseThrow(),
FunctionDescriptor.of(DIV_T, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
// The handle gains a leading SegmentAllocator parameter
System.out.println(div.type()); // (SegmentAllocator,int,int)MemorySegment
try (Arena arena = Arena.ofConfined()) {
MemorySegment r = (MemorySegment) div.invokeExact((SegmentAllocator) arena, 17, 5);
System.out.println(r.get(ValueLayout.JAVA_INT, 0)); // 3
System.out.println(r.get(ValueLayout.JAVA_INT, 4)); // 2
}
}
}Two details are worth noting.
- When the descriptor returns a struct, the handle gets an extra first parameter of type
SegmentAllocator. The linker uses it to allocate the segment that holds the returned struct. AnArenais aSegmentAllocator, so it also decides when that memory is freed. The cast is needed becauseinvokeExactmatches the static type. - The struct layout must match the C layout, including padding.
structLayoutthrowsIllegalArgumentExceptionif a member is misaligned. AddMemoryLayout.paddingLayout(bytes)where C inserts padding.
Descriptor mismatches
The linker accepts any descriptor made of supported layouts. Consider what happens if you describe int abs(int) as JAVA_LONG to JAVA_LONG.
- The linker builds a handle without complaint.
- The call puts a 64-bit value in a register where C expects a 32-bit one. On common platforms the call may appear to work, because the upper bits are ignored.
- Other mismatches corrupt data or crash the JVM: reading a 32-bit result as 64 bits, using
JAVA_INTwhere C returns a pointer, or passing too few arguments so C reads garbage.
None of these produce a Java exception. Treat the descriptor as code that needs the same review as the C header. Check it against the documentation or header for each target platform.
Common errors
- Reversed order. Writing
FunctionDescriptor.of(JAVA_INT, JAVA_LONG)for a function that takes anintand returns along. The return layout is always first. offor a void function.ofneeds a return layout. UseofVoidinstead.- Wrong call-site types. Calling
invokeExactwith a boxed or widened value. Checkhandle.type()and cast to match. - Pointers returned with no target layout. The segment has zero length, and the first access throws
IndexOutOfBoundsException. Usereinterpret(size)or declare a target layout.
Exercise
The C prototype is double pow(double x, double y). Write the FunctionDescriptor. What is the MethodType that toMethodType() returns, and what extra step would you need if the function instead returned a struct by value?
Show answer
Use FunctionDescriptor.of(ValueLayout.JAVA_DOUBLE, ValueLayout.JAVA_DOUBLE, ValueLayout.JAVA_DOUBLE). The method type is (double,double)double. If the function returned a struct by value, you would pass a StructLayout as the return layout. The handle would then take a leading SegmentAllocator parameter, so you would supply an arena (cast to SegmentAllocator for invokeExact) at call time.
Exercise
A teammate describes the C function size_t fread(void *buf, size_t size, size_t n, FILE *f) with JAVA_INT for each size_t. It works on their Linux laptop in a quick test. Why is this still wrong, and what should they use instead?
Show answer
On a 64-bit platform size_t is 64 bits wide. A JAVA_INT descriptor passes and returns only 32 bits, so large sizes are truncated and the register contents above bit 31 are undefined. Small test values can hide this. They should model size_t as JAVA_LONG on 64-bit platforms, or look it up with Linker.nativeLinker().canonicalLayouts().get("size_t") so the width follows the platform.