FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
kvi5hnuCode Sprout team member15 min readOn this page
The previous article called C functions that take numbers, strings and structs. Many C APIs need more than that. Some take a function pointer and call back into the caller's code, such as a comparison function, an event handler or a progress report. Some take a variable number of arguments, like printf. And many report failures through errno, a per-thread error variable. This last article of the course covers all three, which completes the FFM toolbox.
Upcalls
A call from native code into Java is an upcall. C has no idea what a Java method is; it can only call a function pointer. The linker therefore generates a small piece of native code, an upcall stub, that behaves like an ordinary C function. When C calls it, the stub converts the C arguments into Java values, invokes a Java method handle, and passes the result back.

The standard example is qsort from the C library:
void qsort(void *base, size_t count, size_t size, int (*compare)(const void *, const void *));
The last parameter is a pointer to a comparison function that receives pointers to two elements and returns a negative number, zero or a positive number. Three steps produce such a pointer from Java code:
-
Write the Java method and get a
MethodHandlefor it:javastatic int compareFloats(MemorySegment a, MemorySegment b) { return Float.compare(a.get(JAVA_FLOAT, 0), b.get(JAVA_FLOAT, 0)); } ... MethodHandle target = MethodHandles.lookup().findStatic(Solution.class, "compareFloats", MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class)); -
Describe the C signature of the function pointer with a
FunctionDescriptor. The handle's type must match the descriptor:JAVA_INTbecomesint, andADDRESSbecomesMemorySegment. -
Ask the linker for the stub, giving it an arena that controls the stub's lifetime:
javaMemorySegment compare = linker.upcallStub(target, FunctionDescriptor.of(JAVA_INT, ADDRESS.withTargetLayout(JAVA_FLOAT), ADDRESS.withTargetLayout(JAVA_FLOAT)), arena); qsort.invokeExact(array, count, JAVA_FLOAT.byteSize(), compare);
The withTargetLayout calls matter. Without them, the pointers that C passes arrive in Java as zero-length segments, and the get in the comparator fails. With a target layout, each argument segment has the size of a float. withTargetLayout is restricted, and so is upcallStub itself.
Note that the descriptor for qsort uses ofVoid, because qsort returns nothing. Describing it with a return layout would be a descriptor mismatch, the kind of error the linker cannot detect.
Sorting floats through C with a Java comparator is a toy example, since Arrays.sort is simpler and faster. Callbacks matter where a native library drives the work: event loops, audio and video frame handlers, tree walkers and numerical solvers that call a user-supplied function.
Rules for upcalls
- Lifetime. The stub's memory belongs to the arena passed to
upcallStub. When the arena closes, the stub is freed, and a C library that still holds the pointer would jump into freed memory. A stub that C uses only during one call can live in a confined arena around that call. A stub that a library stores, such as a registered event handler, needs an arena that lives as long as the registration, oftenArena.global()or a long-lived shared arena. - Exceptions. An exception cannot propagate through C stack frames. If the target throws, the JVM prints the stack trace with "Unrecoverable uncaught exception encountered" and terminates. A
try/catcharound the downcall does not help. Catch everything inside the upcall and report errors through the return value, or save the exception in a field and rethrow it after the downcall returns. - Threads. Native code may call a stub on any thread, including threads that the native library created itself; such threads are attached to the JVM automatically. The target must then be thread-safe, and it must not touch segments of a confined arena owned by another thread.
- Speed. Each upcall is a transition from native code into the JVM and back. It is cheap but not free, so a callback for every pixel or every sample is costlier than one per buffer.
Binding objects and lambdas
findStatic works for one fixed method. To pass an arbitrary object, such as a Comparator or a lambda, use the java.lang.invoke combinators:
MethodHandle target = MethodHandles.lookup()
.findVirtual(Comparator.class, "compare", MethodType.methodType(int.class, Object.class, Object.class))
.bindTo(byDistance) // the receiver is fixed
.asType(MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
bindTo fixes the receiver object, so that the handle needs only the remaining arguments. asType adapts the generic Object parameters to the MemorySegment types the descriptor requires. MethodHandles.insertArguments similarly fixes any argument, which is the Java counterpart of the void *user_data parameter that many C callback APIs provide. In the other direction, C sometimes hands you a function pointer to call. linker.downcallHandle(descriptor) returns a handle that takes the function address as its first argument.
Variadic functions
A C function declared with ..., such as int printf(const char *format, ...), accepts any number of extra arguments. On several platforms, notably macOS on AArch64, variadic arguments are passed differently from fixed ones. The linker therefore has to know where the fixed parameters end. The option Linker.Option.firstVariadicArg(index) gives the index of the first variadic parameter in the descriptor:
// printf("%s is %d years old\n", name, age)
MethodHandle printf = linker.downcallHandle(linker.defaultLookup().findOrThrow("printf"),
FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_INT),
Linker.Option.firstVariadicArg(1));
The descriptor fixes the number and types of the arguments, so each combination of variadic arguments needs its own handle: a call with two ints needs a different handle from a call with a double. When the patterns are not known in advance, create handles on demand and cache them by descriptor.
Variadic arguments follow C's default argument promotions: a float is passed as a double, and char, short and bool are passed as int. The descriptor must describe the promoted types. The linker rejects JAVA_FLOAT, JAVA_SHORT, JAVA_BYTE, JAVA_CHAR and JAVA_BOOLEAN in variadic positions with an IllegalArgumentException. Write JAVA_DOUBLE or JAVA_INT and convert the value in Java.
Two practical points about printing from C:
- C's
stdouthas its own buffer, separate fromSystem.out. When output goes to a file or a pipe, C output can show up much later than Java output written after it. Flush both:System.out.flush()before the call, andfflush(NULL)(a downcall withMemorySegment.NULL) after it. - To format text for Java,
snprintfinto a native buffer and read the result withgetString. This keeps the output in Java's hands, though Java's ownString.formatis usually the better choice anyway.
Capturing errno
Many C functions signal failure through their return value, such as NULL or -1, and leave the reason in errno: ENOENT when a file does not exist, ERANGE when a number is too large, and so on. errno is per-thread state, usually implemented as a macro, so it cannot be looked up as a symbol. More importantly, reading it with a separate downcall after the call is unreliable, because the JVM itself may call C functions in between (for memory management, for example) and overwrite it.
The option Linker.Option.captureCallState("errno") makes the downcall save errno immediately after the native function returns. The handle then takes an extra first parameter, a segment where the state is stored:
static final StructLayout CAPTURE = Linker.Option.captureStateLayout();
static final VarHandle ERRNO = CAPTURE.varHandle(groupElement("errno"));
...
MethodHandle fopen = linker.downcallHandle(lookup.findOrThrow("fopen"),
FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS), Linker.Option.captureCallState("errno"));
MemorySegment state = arena.allocate(CAPTURE);
var file = (MemorySegment) fopen.invokeExact(state, arena.allocateFrom("data.txt"), arena.allocateFrom("r"));
if (file.equals(MemorySegment.NULL)) {
int errno = (int) ERRNO.get(state, 0L); // base offset 0L, as for every layout var handle
...
}
captureStateLayout() is a platform-specific struct. On Linux and macOS it holds only errno. On Windows it also holds GetLastError (the error code of Win32 API functions) and WSAGetLastError (for sockets), and you can capture several of them at once: captureCallState("GetLastError", "errno"). An unknown name causes an IllegalArgumentException.
errno values are numbers whose meaning is defined by the platform's C headers. Common ones such as ENOENT (2) and ERANGE (34) agree on Linux, macOS and Windows, but many others differ, so convert them to text with strerror or handle only the codes that matter. Read errno only when the function reported a failure. A successful call may leave a stale value from an earlier error.
A C library that calls back
The following example connects all of this with a small C library of your own. The library integrates a mathematical function with Simpson's rule. It takes the function to integrate as a function pointer, and it takes an optional second function pointer for progress reports, which may be NULL:
/* integrate.c: numerical integration of a function supplied by the caller */
#include <stddef.h>
typedef double (*function)(double);
typedef void (*progress)(int done, int total);
/* Simpson's rule on [a, b] with an even number of steps; reports progress every tenth of the work */
double simpson(function f, double a, double b, int steps, progress report) {
if (steps % 2 != 0) steps++;
double h = (b - a) / steps;
double sum = f(a) + f(b);
int every = steps >= 10 ? steps / 10 : 1;
for (int i = 1; i < steps; i++) {
sum += f(a + i * h) * (i % 2 == 0 ? 2 : 4);
if (report != NULL && i % every == 0) report(i, steps);
}
return sum * h / 3;
}
Compile it into a shared library: gcc -O2 -shared -fPIC -o libintegrate.so integrate.c on Linux, clang -O2 -shared -o libintegrate.dylib integrate.c on macOS, or cl /LD /O2 integrate.c (giving integrate.dll) with Visual C++ on Windows. On Windows, also add __declspec(dllexport) before the function so that the DLL exports it.
The Java side passes any DoubleUnaryOperator to C. It binds the operator into the method handle of applyAsDouble and creates a stub for each call. Unlike JNI, there is no generated header, no glue code and no Java-specific symbol name: the C library is a plain library that could be called from any language.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.file.Path;
import java.util.function.DoubleUnaryOperator;
import static java.lang.foreign.ValueLayout.*;
/** Lets a C integration routine call Java functions: java --enable-native-access=ALL-UNNAMED Integrate.java ./libintegrate.so */
public class Integrate {
static final Linker LINKER = Linker.nativeLinker();
static final FunctionDescriptor FUNCTION = FunctionDescriptor.of(JAVA_DOUBLE, JAVA_DOUBLE); // double (*)(double)
static final FunctionDescriptor PROGRESS = FunctionDescriptor.ofVoid(JAVA_INT, JAVA_INT); // void (*)(int, int)
static final MethodHandle APPLY, REPORT;
static {
try {
var lookup = MethodHandles.lookup();
APPLY = lookup.findVirtual(DoubleUnaryOperator.class, "applyAsDouble",
MethodType.methodType(double.class, double.class));
REPORT = lookup.findStatic(Integrate.class, "report", MethodType.methodType(void.class, int.class, int.class));
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
static void report(int done, int total) {
System.out.print(100 * done / total + "% ");
}
final MethodHandle simpson;
@SuppressWarnings("restricted")
Integrate(SymbolLookup library) {
// double simpson(function f, double a, double b, int steps, progress report)
simpson = LINKER.downcallHandle(library.findOrThrow("simpson"),
FunctionDescriptor.of(JAVA_DOUBLE, ADDRESS, JAVA_DOUBLE, JAVA_DOUBLE, JAVA_INT, ADDRESS));
}
/** Integrates any Java function: the operator is bound into a method handle and turned into a C function pointer */
@SuppressWarnings("restricted")
double integrate(DoubleUnaryOperator f, double a, double b, int steps, boolean showProgress) throws Throwable {
try (Arena arena = Arena.ofConfined()) { // the stubs are freed when C no longer needs them
MemorySegment fPointer = LINKER.upcallStub(APPLY.bindTo(f), FUNCTION, arena);
MemorySegment progress = showProgress ? LINKER.upcallStub(REPORT, PROGRESS, arena) : MemorySegment.NULL;
double result = (double) simpson.invokeExact(fPointer, a, b, steps, progress);
if (showProgress) System.out.println();
return result;
}
}
@SuppressWarnings("restricted")
public static void main(String[] args) throws Throwable {
Path library = Path.of(args.length > 0 ? args[0] : System.mapLibraryName("integrate")).toAbsolutePath();
try (Arena arena = Arena.ofConfined()) {
var integrator = new Integrate(SymbolLookup.libraryLookup(library, arena));
System.out.printf("integral of sin on [0, pi] = %.10f (exact: 2)%n",
integrator.integrate(Math::sin, 0, Math.PI, 1000, true));
System.out.printf("integral of x^2 on [0, 3] = %.10f (exact: 9)%n",
integrator.integrate(x -> x * x, 0, 3, 10, false));
double sigma = 1;
System.out.printf("normal density on [-1, 1] = %.10f (about 68.27%%)%n",
integrator.integrate(x -> Math.exp(-x * x / (2 * sigma * sigma)) / Math.sqrt(2 * Math.PI), -1, 1, 200, false));
}
}
}
Running java --enable-native-access=ALL-UNNAMED Integrate.java ./libintegrate.dylib on macOS prints:
10% 20% 30% 40% 50% 60% 70% 80% 90%
integral of sin on [0, pi] = 2.0000000000 (exact: 2)
integral of x^2 on [0, 3] = 9.0000000000 (exact: 9)
normal density on [-1, 1] = 0.6826894922 (about 68.27%)
Some details worth noting:
APPLYis a handle for the interface methodapplyAsDouble, with the receiver as its first parameter.bindTo(f)turns it into a(double)doublehandle that matches the descriptor of the C function pointer exactly.- The stubs live in a confined arena around a single call to
simpson. C does not keep the pointers after returning, so this lifetime is long enough. - The progress pointer is optional. Passing
MemorySegment.NULLmakes C skip the reports. - Simpson's rule is exact for polynomials up to degree three, which is why
x^2comes out exactly 9 with only 10 steps. - If a lambda threw an exception, for example a
NullPointerException, the JVM would terminate. A robust version would catch exceptions inside the operator and returnDouble.NaN.
The program
The demo calls only the C standard library, so it runs on Linux, macOS and Windows. It sorts floats and structs with Java comparators called from qsort, formats text with the variadic snprintf, prints with printf, and captures errno from strtoll and fopen. As in the previous article, the restricted calls print a warning on standard error unless the program runs with --enable-native-access=ALL-UNNAMED; the output below shows standard output.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.VarHandle;
import java.util.Arrays;
import java.util.Comparator;
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
import static java.lang.foreign.ValueLayout.*;
public class Solution {
static final Linker LINKER = Linker.nativeLinker();
static final SymbolLookup LIBC = LINKER.defaultLookup();
static int comparisons;
@SuppressWarnings("restricted")
static MethodHandle downcall(String name, FunctionDescriptor descriptor, Linker.Option... options) {
return LINKER.downcallHandle(LIBC.findOrThrow(name), descriptor, options);
}
// void qsort(void *base, size_t count, size_t size, int (*compare)(const void *, const void *))
static final MethodHandle QSORT = downcall("qsort", FunctionDescriptor.ofVoid(ADDRESS, JAVA_LONG, JAVA_LONG, ADDRESS));
// the Java method that C calls back: compares two floats given by pointers
static int compareFloats(MemorySegment a, MemorySegment b) {
comparisons++;
return Float.compare(a.get(JAVA_FLOAT, 0), b.get(JAVA_FLOAT, 0));
}
public static void main(String[] args) throws Throwable {
upcalls();
upcallsWithObjects();
variadic();
errno();
}
@SuppressWarnings("restricted")
static void upcalls() throws Throwable {
System.out.println("== Upcalls: qsort calls a Java comparator ==");
MethodHandle target = MethodHandles.lookup().findStatic(Solution.class, "compareFloats",
MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
// the pointers C passes in become segments sized by the target layout
FunctionDescriptor compareDesc = FunctionDescriptor.of(JAVA_INT,
ADDRESS.withTargetLayout(JAVA_FLOAT), ADDRESS.withTargetLayout(JAVA_FLOAT));
try (Arena arena = Arena.ofConfined()) {
MemorySegment compare = LINKER.upcallStub(target, compareDesc, arena); // a C function pointer
System.out.println("upcall stub: a native function pointer, size " + compare.byteSize()
+ ", address non-zero " + (compare.address() != 0));
float[] values = { 3.5f, -1f, 2.25f, 0f, 10f, -7.5f, 2.25f, 1f };
MemorySegment array = arena.allocateFrom(JAVA_FLOAT, values);
QSORT.invokeExact(array, (long) values.length, JAVA_FLOAT.byteSize(), compare);
System.out.println("sorted by C: " + Arrays.toString(array.toArray(JAVA_FLOAT))
+ "; the Java comparator ran: " + (comparisons > 0));
}
}
static final StructLayout POINT = MemoryLayout.structLayout(JAVA_INT.withName("x"), JAVA_INT.withName("y"));
static final VarHandle X = POINT.varHandle(groupElement("x"));
static final VarHandle Y = POINT.varHandle(groupElement("y"));
@SuppressWarnings("restricted")
static void upcallsWithObjects() throws Throwable {
System.out.println();
System.out.println("== An upcall bound to an object: sorting structs with a Comparator ==");
Comparator<MemorySegment> byDistance = Comparator.comparingInt(
(MemorySegment p) -> { int x = (int) X.get(p, 0L), y = (int) Y.get(p, 0L); return x * x + y * y; })
.thenComparingInt(p -> (int) X.get(p, 0L));
// Comparator.compare(Object, Object) bound to this comparator, then adapted to (MemorySegment, MemorySegment)int
MethodHandle target = MethodHandles.lookup()
.findVirtual(Comparator.class, "compare", MethodType.methodType(int.class, Object.class, Object.class))
.bindTo(byDistance)
.asType(MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
try (Arena arena = Arena.ofConfined()) {
MemorySegment compare = LINKER.upcallStub(target,
FunctionDescriptor.of(JAVA_INT, ADDRESS.withTargetLayout(POINT), ADDRESS.withTargetLayout(POINT)), arena);
int[][] points = { {3, 4}, {-1, 0}, {0, 2}, {5, -5}, {1, 1}, {-3, -4} };
MemorySegment array = arena.allocate(POINT, points.length);
for (int i = 0; i < points.length; i++) {
X.set(array, i * POINT.byteSize(), points[i][0]);
Y.set(array, i * POINT.byteSize(), points[i][1]);
}
QSORT.invokeExact(array, (long) points.length, POINT.byteSize(), compare);
var sb = new StringBuilder("by distance from the origin:");
array.elements(POINT).forEach(p -> sb.append(" (").append((int) X.get(p, 0L)).append(",")
.append((int) Y.get(p, 0L)).append(")"));
System.out.println(sb);
}
}
// int snprintf(char *buffer, size_t size, const char *format, ...)
static final MethodHandle SNPRINTF = downcall("snprintf",
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, JAVA_INT, JAVA_DOUBLE),
Linker.Option.firstVariadicArg(3)); // the arguments after the format vary
// int printf(const char *format, ...) with one int argument, and int fflush(FILE *stream)
static final MethodHandle PRINTF_INT = downcall("printf",
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT), Linker.Option.firstVariadicArg(1));
static final MethodHandle FFLUSH = downcall("fflush", FunctionDescriptor.of(JAVA_INT, ADDRESS));
static void variadic() throws Throwable {
System.out.println();
System.out.println("== Variadic functions ==");
try (Arena arena = Arena.ofConfined()) {
MemorySegment buffer = arena.allocate(64);
int n = (int) SNPRINTF.invokeExact(buffer, buffer.byteSize(),
arena.allocateFrom("%s scored %d points (%.2f%%)"),
arena.allocateFrom("Ada"), 42, 87.456);
System.out.println("snprintf wrote " + n + " chars: " + buffer.getString(0));
System.out.flush();
int printed = (int) PRINTF_INT.invokeExact(arena.allocateFrom("printf from C: %d\n"), 2026);
int flushed = (int) FFLUSH.invokeExact(MemorySegment.NULL); // C's stdout has its own buffer
System.out.println("printf returned " + printed + ", fflush " + flushed);
}
try {
downcall("printf", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_FLOAT), Linker.Option.firstVariadicArg(1));
} catch (IllegalArgumentException e) {
System.out.println("a float variadic argument: IllegalArgumentException (C promotes float to double)");
}
}
static final StructLayout CAPTURE = Linker.Option.captureStateLayout();
static final VarHandle ERRNO = CAPTURE.varHandle(groupElement("errno"));
// long long strtoll(const char *s, char **end, int base), FILE *fopen(const char *path, const char *mode)
static final MethodHandle STRTOLL = downcall("strtoll",
FunctionDescriptor.of(JAVA_LONG, ADDRESS, ADDRESS, JAVA_INT), Linker.Option.captureCallState("errno"));
static final MethodHandle FOPEN = downcall("fopen",
FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS), Linker.Option.captureCallState("errno"));
static void errno() throws Throwable {
System.out.println();
System.out.println("== Capturing errno ==");
System.out.println("capture state layout: " + CAPTURE.memberLayouts().stream()
.map(l -> l.name().orElse("?")).toList() + ", size " + CAPTURE.byteSize());
try (Arena arena = Arena.ofConfined()) {
MemorySegment state = arena.allocate(CAPTURE); // passed as an extra first argument
long big = (long) STRTOLL.invokeExact(state, arena.allocateFrom("99999999999999999999"), MemorySegment.NULL, 10);
System.out.println("strtoll overflow: result " + big + " (Long.MAX_VALUE " + (big == Long.MAX_VALUE)
+ "), errno " + (int) ERRNO.get(state, 0L) + " (ERANGE)");
var file = (MemorySegment) FOPEN.invokeExact(state, arena.allocateFrom("no/such/dir/file.txt"),
arena.allocateFrom("r"));
System.out.println("fopen of a missing file: NULL " + file.equals(MemorySegment.NULL)
+ ", errno " + (int) ERRNO.get(state, 0L) + " (ENOENT)");
}
try {
downcall("strlen", FunctionDescriptor.of(JAVA_LONG, ADDRESS), Linker.Option.captureCallState("no_such_state"));
} catch (IllegalArgumentException e) {
System.out.println("unknown capture state name: IllegalArgumentException");
}
}
}
== Upcalls: qsort calls a Java comparator ==
upcall stub: a native function pointer, size 0, address non-zero true
sorted by C: [-7.5, -1.0, 0.0, 1.0, 2.25, 2.25, 3.5, 10.0]; the Java comparator ran: true
== An upcall bound to an object: sorting structs with a Comparator ==
by distance from the origin: (-1,0) (1,1) (0,2) (-3,-4) (3,4) (5,-5)
== Variadic functions ==
snprintf wrote 29 chars: Ada scored 42 points (87.46%)
printf from C: 2026
printf returned 20, fflush 0
a float variadic argument: IllegalArgumentException (C promotes float to double)
== Capturing errno ==
capture state layout: [errno], size 4
strtoll overflow: result 9223372036854775807 (Long.MAX_VALUE true), errno 34 (ERANGE)
fopen of a missing file: NULL true, errno 2 (ENOENT)
unknown capture state name: IllegalArgumentException
Points to notice:
- The upcall stub is a zero-length segment: like a function symbol, it is an address of code, not data.
- Thanks to the target layouts, the comparators could read the
floatand thePOINTstruct behind each pointer. - The
Comparatorobject was bound into the handle withbindTo, andasTypeadaptedObjecttoMemorySegment. snprintfreturned 29, the length of the formatted text, and%.2frounded 87.456 to 87.46.- The C line printed by
printfappeared in order because Java flushed before the call and C flushed after it. - A
floatin a variadic position was rejected when the handle was created. - The capture state layout on macOS contains only
errno. On Windows it would also listGetLastErrorandWSAGetLastError. strtollreturnedLong.MAX_VALUEand set errno toERANGE(34);fopenreturned NULL and set errno toENOENT(2).
Common questions
How do I pass a Java callback to qsort or a similar C function?
Create a method handle for a static Java method with matching types, then linker.upcallStub(handle, descriptor, arena). Pass the resulting segment as the function pointer. The stub stays valid until its arena closes, so keep the arena open as long as C may call it.
What happens if my callback throws an exception? The JVM can't propagate it through C frames, so it prints the exception and terminates the process. Catch everything inside upcalls and report errors through return values or state.
How do I call printf or other variadic functions?
Describe the actual arguments of this call in the FunctionDescriptor and pass Linker.Option.firstVariadicArg(index). Promote types as C does: float becomes double, and char, short and boolean become int. The linker rejects the unpromoted types.
How do I read errno after a call?
Use Linker.Option.captureCallState("errno"), allocate a segment of Linker.Option.captureStateLayout(), pass it as the first argument, and read errno from it with a var handle after the call. Reading errno with a separate downcall is unreliable, because the JVM may change it in between.
Where do I go after this course? Practice by building something end to end: a small desktop tool with Swing, an HTTP service with the JDK server and JDBC, or a native integration with FFM. Read the JEPs of new releases (openjdk.org/jeps) and the JDK release notes to stay current, and use the API documentation of your JDK version as the reference.
API reference
| Class / method | Purpose |
|---|---|
Linker.upcallStub(target, descriptor, arena, options...) | A C function pointer that calls a Java method handle (restricted). |
MethodHandles.lookup().findStatic, findVirtual, MethodType.methodType | Method handles for upcall targets. |
MethodHandle.bindTo, asType, MethodHandles.insertArguments | Binding receivers and arguments, adapting types. |
ADDRESS.withTargetLayout(layout) | Sized pointer arguments in upcalls. |
Linker.downcallHandle(descriptor) | Calling a function pointer received from C. |
Linker.Option.firstVariadicArg(index) | Calling variadic functions. |
Linker.Option.captureCallState(names...), captureStateLayout() | Saving errno, GetLastError and WSAGetLastError. |
MemorySegment.NULL | NULL arguments, such as an absent callback or fflush(NULL). |
Summary
- An upcall stub, created by
Linker.upcallStubfrom a method handle and a function descriptor, is a native function pointer that calls Java code. Give pointer parameters a target layout so that the Java side can read through them. - The stub lives as long as its arena. Keep it alive while native code may call it. An exception that escapes an upcall terminates the JVM, so catch everything inside.
bindTo,insertArgumentsandasTypeturn objects and lambdas into upcall targets.- Variadic functions need
firstVariadicArgand one handle per argument pattern, with promoted types (doubleinstead offloat,intinstead of smaller integers). captureCallState("errno")saves errno right after the call into a segment ofcaptureStateLayout(), passed as an extra first argument. Read it through a var handle with base offset0L, and only after a reported failure.
Practice Questions
1. A program registers an upcall stub as an event handler with a native library, creating the stub in a confined arena inside a method that returns right after registration. What goes wrong?
The arena is closed when the method returns, which frees the stub's code. The library keeps the function pointer and calls it later, when the next event arrives, and jumps into freed memory, typically crashing the process. A handler that outlives the registering call needs an arena that lives as long as the registration: Arena.global() for handlers that are never removed, or a shared arena that is closed only after the handler has been unregistered. And because events often arrive on library threads, the arena must not be confined.
2. Why can't a Java upcall simply throw an exception to signal an error to the calling code?
Between the Java code that made the downcall and the upcall target are C stack frames, such as qsort's. C has no notion of Java exceptions, so unwinding through those frames would skip C's cleanup and leave its state inconsistent. The FFM API does not try: an uncaught exception in an upcall prints a message and terminates the JVM. Catch exceptions inside the target and signal the problem through the return value (or a flag), then, after the downcall returns, check the flag and throw a Java exception in Java code.
3. Write the handle for printf("%.3f and %c\n", x, c), where x is a float and c a char.
Both are variadic arguments, so they are promoted: the float is passed as a C double and the char as an int. The descriptor is FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_DOUBLE, JAVA_INT) with Linker.Option.firstVariadicArg(1), and the call is (int) printf.invokeExact(format, (double) x, (int) c). Using JAVA_FLOAT or JAVA_CHAR would make the linker throw IllegalArgumentException when the handle is created.
4. Why not read errno by calling a C function such as __errno_location after the downcall?
Between the native function returning and the second downcall, the JVM may run its own native code, for example for garbage collection, JIT compilation or thread management, and any of it can change errno. The function is also platform-specific (__errno_location in glibc, __error on macOS, _errno on Windows). captureCallState copies errno inside the downcall stub, immediately after the target returns and before the JVM does anything else, so the value is reliable and the code is portable.
5. When would you still choose JNI over the FFM API?
FFM covers what JNI was mostly used for, calling existing C libraries, with pure Java code, no compiler, safer memory access and comparable or better performance. JNI remains relevant for existing code bases, for native code that must manipulate Java objects directly (create objects, call methods and access fields from C through the JNIEnv), and on Java versions before 22. Note that both are now treated the same way regarding integrity: since JDK 24, JNI library loading and native methods are also subject to --enable-native-access warnings (JEP 472).
Where to go from here
This article completes the second Core Java course. It began with streams, input and output, files and regular expressions, and went on to XML, networking, database programming with JDBC, the date and time API, and internationalization. Then came the compiler and scripting APIs and security. Three parts on desktop programming followed: Swing and its components, tables and trees, Java 2D graphics, images and printing. The course ended, in this last part, with the native interfaces: JNI and the Foreign Function and Memory API.
Every topic was a door into a larger field. Good next steps are the official JDK documentation and the Java Language Specification, the JEPs behind recent features (they explain both how features work and why they were designed that way), and above all, writing programs that combine these libraries. Return to any article when you need a refresher, and good luck with your projects.
Previous: Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract Back to the start: Java Streams Explained: From Loops to Stream Pipelines
Related reading
- Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
- FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
- Foreign Function and Memory API: Arenas and Memory Segments
- Native Methods with JNI: Calling C Code from Java
- Printing in Java: Print Jobs, Multipage Printing and Print Services

More in Core Java II
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Native Methods with JNI: Calling C Code from Java
The Java Native Interface: declaring native methods, generating headers with javac -h, JNI function naming and type mapping, strings and modified UTF-8, arrays, calling Java from C, exceptions, references, building and loading libraries, native access restrictions, and why the FFM API replaces JNI.
Discussion
Sign in to ask a question or share what you learned.