Java tutorial · Advanced · 13 min
Calling an existing C++ library from Java with the FFM API
In capital markets, valuation engines are often written in C++ and battle-tested over years. Rewriting them in Java is slow and risky; JNI, the old bridge, means writing and maintaining C glue code. Since Java 22, the Foreign Function & Memory API (FFM, JEP 454) lets you call the library directly from Java.
Tested source code, free to use: GitHub, Scopas-Team/java-finance-tutorials (Apache 2.0 licence)
1. Expose a C interface on the C++ side
Java cannot call a C++ class method: names are mangled by the compiler and C++ exceptions mean nothing to the JVM. So you expose a few extern "C" functions that wrap the existing code:
pricer_api.cpp
#include "BlackScholes.hpp" // the existing C++ code
extern "C" {
// Returns 0 on success, an error code otherwise; the price is written to *price.
int call_price(double spot, double strike, double vol, double rate, double maturity, double* price) {
try {
*price = pricing::BlackScholes(spot, strike, vol, rate, maturity).call();
return 0;
} catch (const std::exception&) {
return 1; // no C++ exception may cross the boundary
}
}
double discount_factor(const double* times, const double* rates, int n, double t) {
return pricing::Curve(times, rates, n).discount(t);
}
}
# Linux
g++ -shared -fPIC -O2 -o libpricer.so pricer_api.cpp BlackScholes.cpp
# Windows (MSVC): add __declspec(dllexport) before the functions, then
cl /LD /O2 pricer_api.cpp BlackScholes.cpp /Fe:pricer.dll
2. Calling a function from Java
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.nio.file.Path;
import static java.lang.foreign.ValueLayout.*;
public final class Pricer {
private static final Linker LINKER = Linker.nativeLinker();
private static final SymbolLookup LIB =
SymbolLookup.libraryLookup(Path.of("lib/libpricer.so"), Arena.global());
private static final MethodHandle CALL_PRICE = LINKER.downcallHandle(
LIB.find("call_price").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, JAVA_DOUBLE, JAVA_DOUBLE, JAVA_DOUBLE, JAVA_DOUBLE, JAVA_DOUBLE, ADDRESS));
public static double callPrice(double spot, double strike, double vol, double rate, double maturity) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment price = arena.allocate(JAVA_DOUBLE); // slot for the result
int code = (int) CALL_PRICE.invokeExact(spot, strike, vol, rate, maturity, price);
if (code != 0) throw new PricingException("call_price failed, code " + code);
return price.get(JAVA_DOUBLE, 0);
} catch (PricingException e) {
throw e;
} catch (Throwable t) {
throw new IllegalStateException("native call failed", t);
}
}
}
FunctionDescriptordescribes the C signature: return type, then parameters.invokeExactrequires types identical to the descriptor, hence the(int)cast.- The
Arenamanages the lifetime of native memory: at the end of thetry, it is freed.
3. Passing arrays: a yield curve
private static final MethodHandle DISCOUNT = LINKER.downcallHandle(
LIB.find("discount_factor").orElseThrow(),
FunctionDescriptor.of(JAVA_DOUBLE, ADDRESS, ADDRESS, JAVA_INT, JAVA_DOUBLE));
public static double discountFactor(double[] times, double[] rates, double t) throws Throwable {
try (Arena arena = Arena.ofConfined()) {
MemorySegment ts = arena.allocateFrom(JAVA_DOUBLE, times); // copied into native memory
MemorySegment rs = arena.allocateFrom(JAVA_DOUBLE, rates);
return (double) DISCOUNT.invokeExact(ts, rs, times.length, t);
}
}
Native memory lives outside the Java heap: the garbage collector does not move it, and the C++ library can read it without an extra copy. If the library keeps a pointer after the call, you need an arena that lives as long as it does (for example Arena.ofShared(), closed explicitly).
4. Generating bindings with jextract
Writing descriptors by hand becomes tedious on a large API. OpenJDK's jextract tool reads the C header and generates the matching Java classes:
jextract --output src/main/java --target-package com.bank.pricer.nativelib \
--library pricer pricer_api.h
5. Running it without crashing the JVM
java --enable-native-access=ALL-UNNAMED -jar pricing-service.jar
Without this option the JVM prints a warning on native access; future versions may refuse it. With modules, name the module instead of ALL-UNNAMED.
- An error in native code stops the whole JVM: there is no exception to catch. For a fragile library, isolate it in a separate process that can restart on its own.
- No C++ exception across the boundary: catch everything in the
extern "C"functions and return an error code. - Check thread safety: a library with global state does not always support concurrent calls.
- Memory ownership: who allocates, who frees? Write it in the header.
- Virtual threads: a native call pins the virtual thread to its OS thread. For long calculations, use a pool of platform threads.
- Regression tests: compare prices obtained through Java and through the current C++ application over a large set of scenarios.
C++ legacy to modernise?
Reuse, wrap or rewrite: our legacy diagnostic assesses your applications and proposes the least risky path.