Sub topic 13
Calling variadic functions such as printf
This chapter assumes you can already build a downcall handle from a Linker, a symbol and a FunctionDescriptor. Here you will handle C functions that take a variable number of arguments.
What makes a variadic function different
A variadic function ends its C parameter list with .... The standard example is int printf(const char *format, ...). The caller decides how many extra arguments to pass and what types they have. The format string tells the function how to read them.
On many platforms, variadic calls use different argument-passing rules than ordinary calls. The linker cannot guess where the fixed arguments end, so you must tell it.
Marking the variadic arguments
Pass Linker.Option.firstVariadicArg(int index) when you create the handle. The index is the position in the FunctionDescriptor of the first variadic argument. For printf, the format string is at index 0, so the variadic part starts at index 1.
A variadic handle has a fixed signature. The descriptor lists the exact types for one particular call shape. If you want to call printf with (int, double) and also with (long), create two handles.
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 PrintfDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle printf = linker.downcallHandle(
linker.defaultLookup().find("printf").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT,
ValueLayout.ADDRESS, // const char *format
ValueLayout.JAVA_INT, // first variadic argument
ValueLayout.JAVA_DOUBLE), // second variadic argument
Linker.Option.firstVariadicArg(1));
try (Arena arena = Arena.ofConfined()) {
MemorySegment format = arena.allocateUtf8String("count=%d ratio=%.2f\n");
int written = (int) printf.invokeExact(format, 42, 3.14);
System.out.println("printf wrote " + written + " characters");
}
}
}This is written for Java 22. In Java 23 and later, use allocateFrom instead of allocateUtf8String. Run it with --enable-native-access=ALL-UNNAMED. It prints count=42 ratio=3.14 and then printf wrote 20 characters.
Type rules for variadic arguments
C promotes small types when they are passed through .... The FFM API makes you do that choice explicitly.
| C type | Layout to use | Notes |
|---|---|---|
| `int`, `char`, `short` | `JAVA_INT` | Pass an `int`. Small types are promoted to `int` in C. |
| `long` | `JAVA_LONG` | `long` is 32 bits on 64-bit Windows, so check the platform. |
| `float`, `double` | `JAVA_DOUBLE` | `float` is promoted to `double`. |
| pointers, strings | `ADDRESS` | Pass a `MemorySegment`. |
The linker rejects JAVA_BYTE, JAVA_SHORT, JAVA_CHAR, JAVA_BOOLEAN and JAVA_FLOAT as variadic argument layouts. It throws an IllegalArgumentException when you create the handle.
Common errors
- Forgetting the option. The call may still run on some platforms, but it is undefined behavior on others. For example, floating-point arguments can be passed in the wrong registers.
- Mismatched format and arguments. The linker cannot check that
%dmatches anint. A wrong format string can read garbage or crash the JVM. - Wrong index. The index counts from the start of the descriptor, not from the start of the
.... - Output order.
printfwrites to the Cstdoutbuffer, not toSystem.out. When output is redirected to a file or pipe, the C text can appear after the Java text.
Exercise
You want to call int snprintf(char *buf, size_t n, const char *fmt, ...) with one long argument. What index do you pass to firstVariadicArg, and which layout do you use for the long?
Show answer
Pass 3, because buf, n and fmt occupy indexes 0, 1 and 2, so the variadic part starts at index 3. Use JAVA_LONG for a C long on Linux and macOS 64-bit, where it is 64 bits. On 64-bit Windows a C long is 32 bits, so use JAVA_INT there.