Sub topic 14
Generating bindings with jextract
Earlier chapters built bindings by hand. For each C function you looked up a symbol, wrote a FunctionDescriptor and created a downcall handle. For each struct you wrote a StructLayout and computed offsets. This works, but it is repetitive, and one wrong layout or descriptor can crash the JVM. jextract reads a C header file and generates that code for you.
This chapter assumes you have read the chapters on memory layouts, downcall handles and arenas. You also need a JDK 22 or later, a C compiler, and enough C to read a header file.
What jextract is
jextract is a command-line tool that parses C headers with libclang and writes Java classes that use java.lang.foreign. Three facts matter before you use it:
- It is not part of the JDK. You download it separately from the OpenJDK project, and the download includes the libclang it needs.
- It runs at build time. The generated classes are ordinary Java that depends only on the standard FFM API, so
jextractis not needed at run time. - Use a build that matches your JDK. The generated code calls FFM methods whose names changed between Java 22 and later releases.
What it generates
For each header, jextract produces a main class named after the header. By default it is the header name with _h appended, so geometry.h becomes geometry_h. You can change this name with an option. The output has these parts:
| C construct | Generated Java |
|---|---|
| Function | A static method that wraps a cached downcall handle |
| Struct or union | A class with `layout()`, `allocate(...)`, and a getter and setter per field |
| Macro constant or enum constant | A static method that returns the value, such as `MAX_POINTS()` |
| Global variable | Static getter and setter methods |
| Function pointer typedef | A class with an `allocate(...)` method that builds an upcall stub |
The generated code is the same code you would write by hand. It holds a FunctionDescriptor and a MethodHandle for each function and exposes them through a typed method. It also carries the struct layouts.
A worked example
You will bind a small library with one struct, two functions and one constant. First, the header geometry.h:
#ifndef GEOMETRY_H
#define GEOMETRY_H
#define MAX_POINTS 16
typedef struct {
int x;
int y;
} Point;
int point_sum(const Point *p);
void point_scale(Point *p, int factor);
#endifNext, the implementation geometry.c:
#include "geometry.h"
int point_sum(const Point *p) {
return p->x + p->y;
}
void point_scale(Point *p, int factor) {
p->x *= factor;
p->y *= factor;
}Build the shared library, then run jextract. The commands below are for Linux. On macOS the library is libgeometry.dylib, and on Windows it is geometry.dll.
cc -shared -fPIC -o libgeometry.so geometry.c
jextract \
--output src \
--target-package com.example.geometry \
--library geometry \
geometry.hThe options mean the following:
--outputis the directory that receives the generated files.--target-packageis the Java package for them.--library geometrynames a library the generated code should load. On current builds, the generated class does this withSystem.loadLibrary("geometry"). Without this option, the generated code can only find symbols that are already loaded.
Look in src/com/example/geometry. You should see geometry_h and Point, plus a few helper classes. Open Point and compare it with the StructLayout you wrote by hand in an earlier chapter. It has the same two JAVA_INT fields named x and y.
Now write the application, app/Main.java:
package app;
import com.example.geometry.Point;
import com.example.geometry.geometry_h;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
public class Main {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment p = Point.allocate(arena);
Point.x(p, 3);
Point.y(p, 4);
System.out.println(geometry_h.point_sum(p)); // 7
geometry_h.point_scale(p, 10);
System.out.println(Point.x(p) + "," + Point.y(p)); // 30,40
System.out.println(geometry_h.MAX_POINTS()); // 16
}
}
}Compile and run it. The generated code calls restricted methods, so you still need to enable native access. You also need to tell the JVM where libgeometry.so is.
javac -d out $(find src app -name '*.java')
java --enable-native-access=ALL-UNNAMED \
-Djava.library.path=. \
-cp out app.MainThe Point.allocate(arena) call allocates 8 bytes in your arena, sized from the generated layout. Point.x(p, 3) writes at the right offset. You never write an offset, a layout or a descriptor yourself, and the arena still controls the lifetime of the memory.
Controlling what gets generated
A real header can pull in a lot of other headers. Running jextract on <stdio.h> or a large library header generates thousands of declarations. You can narrow the output in two steps.
First, dump the list of declarations to a file:
jextract --dump-includes includes.txt geometry.hThe file has one option line per declaration, all commented out. Delete the lines you do not want, uncomment the rest, and pass the file back as an argument file with the @ prefix:
jextract @includes.txt --output src --target-package com.example.geometry geometry.hYou can also filter on the command line with options such as --include-function, --include-struct and --include-constant. When your headers need extra search paths or macros, use -I for include directories and -D for definitions. Check jextract --help for the options your build supports, because the tool is still evolving.
Keep the options in an argument file under version control, and run jextract from your build script. Treat the generated sources as build output. Do not edit them by hand, because the next run overwrites your changes.
Things the generated code does not do for you
jextract removes boilerplate, but it does not change the rules of native memory.
- Pointers have no size. A C
char *orPoint *becomes aMemorySegmentof length zero. You can pass it to another native function, but you cannot read it until you resize it withreinterpret. That method is restricted, and you must supply a size that you know is correct from the library's documentation. - Lifetimes are still yours.
Point.allocate(arena)ties the memory to the arena. If you close the arena while native code still holds the pointer, you get a dangling pointer, exactly as with hand-written code. - Platform types follow the machine that ran
jextract. The tool resolveslong,size_tand similar types for the platform where it ran. Generated code from Linux may use a differentlongsize than Windows would. Runjextracton, or for, each platform you ship. - Struct returns and by-value structs need an allocator. A function that returns a struct by value takes a
SegmentAllocatoras its first parameter, because the result needs a place to live. - Variadic functions need extra care. Variadic functions such as
printfget generated wrappers that take the variadic arguments in a special form. Check the generated signature before you call one. - Native access is still restricted. The generated code does not bypass the restricted-method checks. Pass
--enable-native-accessfor the module or class path that contains it.
When to use jextract and when not to
Use jextract when the library has many functions or structs, when the header changes between releases, or when struct layouts are large or nested. It removes a whole class of layout mistakes.
Write the bindings by hand when you need only one or two functions, when you want no build-time tool dependency, or when you must adapt the signatures, such as modeling a size_t in a particular way. The strlen and qsort examples from earlier chapters are about the size where hand-written code is simpler.
Exercise
You run jextract on a header that declares const char *get_name(void);. Your code calls geometry_h.get_name() and then tries to read a string from the returned segment, but it fails. What is the cause and how do you fix it?
Show answer
The generated method returns a MemorySegment of length zero, because the C pointer carries no size information. Reading from it is out of bounds. Resize it with reinterpret(size) if you know the size, or use getUtf8String(0) (Java 22) or getString(0) (Java 23 and later) on a segment reinterpreted to Long.MAX_VALUE bytes, which reads up to the null terminator. Both uses of reinterpret are restricted methods, so run with --enable-native-access.
Exercise
Why should you commit the jextract argument file to version control but usually not the generated Java sources?
Show answer
The argument file records the inputs: the header, the package, the library name and the include filters. Anyone can regenerate the output from it, and the generated sources depend on the JDK and the platform. Generating them in the build keeps them consistent with the headers and the target environment.