JNI
suggest changeJNI (Java Native Interface) lets code running on the JVM call functions written in C, C++, Rust or any other language that can export C functions, and lets that native code call back into the JVM. Kotlin/JVM compiles to ordinary JVM bytecode, so it uses JNI the same way Java does.
Reasons to go native:
- use an existing C/C++ library (an image codec, a database engine, a hardware SDK)
- call an operating system API the JDK doesn't expose
- run a hot loop that you've measured to be faster in C (this is rarer than people think; the JIT is good)
JNI is old (it shipped with Java 1.1) and verbose. Since JDK 22 there's a better option for most cases, the Foreign Function & Memory API (java.lang.foreign), covered at the end of this article. JNI is still worth knowing: lots of existing libraries use it, Android uses it (the NDK), and it's the only way for native code to work with JVM objects directly.
This article covers:
- declaring native functions with
external - naming the C functions and building a shared library on Windows, Linux and macOS
- loading the library and the JDK 24+ native access warning
- strings, arrays and Kotlin objects in C
- calling Kotlin from C and throwing exceptions
- keeping native resources behind an
AutoCloseablehandle RegisterNatives, threads and references- the FFM API (
java.lang.foreign) as the modern alternative
The examples were compiled with Kotlin 2.4 and JDK 25 on Windows, using clang from Visual Studio's LLVM toolset and MSVC's cl.exe.
The external keyword
Java marks a method implemented in native code with native. Kotlin uses external:
package demo
object NativeMath {
init {
System.loadLibrary("nativemath") // nativemath.dll / libnativemath.so / libnativemath.dylib
}
external fun add(a: Int, b: Int): Int
external fun greet(name: String): String
}
fun main() {
println(NativeMath.add(2, 40))
println(NativeMath.greet("Kotlin"))
}
An external function has no body. The compiler emits a JVM method with the native flag, and the JVM looks for the implementation in the loaded native libraries the first time it's called.
The init block of the object runs once, the first time NativeMath is used, so the library is loaded before any of its functions can be called. In a regular class you'd put the init block in the companion object.
Writing the C side
The JVM finds the C function by name. For a method greet in class demo.NativeMath the name is Java_demo_NativeMath_greet:
#include <jni.h>
#include <stdio.h>
JNIEXPORT jint JNICALL
Java_demo_NativeMath_add(JNIEnv *env, jobject self, jint a, jint b) {
return a + b;
}
JNIEXPORT jstring JNICALL
Java_demo_NativeMath_greet(JNIEnv *env, jobject self, jstring name) {
const char *utf = (*env)->GetStringUTFChars(env, name, NULL);
if (utf == NULL) return NULL; /* OutOfMemoryError already thrown */
char buf[256];
snprintf(buf, sizeof buf, "Hello, %s, from C!", utf);
(*env)->ReleaseStringUTFChars(env, name, utf);
return (*env)->NewStringUTF(env, buf);
}
Every JNI function gets two extra parameters before its real arguments:
JNIEnv *envis a pointer to a table of functions for working with the JVM: creating strings, reading arrays, calling methods, throwing exceptions. In C you call them as(*env)->Fn(env, ...). In C++env->Fn(...)works.- the second parameter is the receiver. For an instance method (including methods of an
object, which are instance methods on itsINSTANCEsingleton) it's ajobject. For a static method (@JvmStaticin a companion object, or a top-level function) it's thejclass.
JNIEXPORT makes the function visible outside the library (__declspec(dllexport) on Windows) and JNICALL sets the calling convention.
The Kotlin types map to C types like this:
| Kotlin | JNI C type | Signature |
|---|---|---|
Boolean |
jboolean (unsigned 8-bit) |
Z |
Byte |
jbyte |
B |
Char |
jchar (unsigned 16-bit) |
C |
Short |
jshort |
S |
Int |
jint |
I |
Long |
jlong |
J |
Float |
jfloat |
F |
Double |
jdouble |
D |
Unit (return) |
void |
V |
String |
jstring |
Ljava/lang/String; |
IntArray |
jintArray |
[I |
ByteArray |
jbyteArray |
[B |
| any other class | jobject |
Lpkg/Name; |
Nullable primitives (Int?) are boxed java.lang.Integer objects, and so are Kotlin's unsigned types and value classes in some positions. Stick to non-null primitives, String and primitive arrays in external signatures.
Naming rules
The function name is Java_ + fully qualified class name with . replaced by _ + _ + method name. Characters that aren't valid in C identifiers are escaped:
_in a name becomes_1(methodcrc_32becomes..._crc_132);becomes_2,[becomes_3, non-ASCII characters become_0xxxx
For top-level functions the class is the file facade: external fun foo() in Hashing.kt with package demo lives in demo.HashingKt, so the C name is Java_demo_HashingKt_foo. Use @file:JvmName("Hashing") to get a nicer name.
Java developers run javac -h to generate a header with all the names. That doesn't work for Kotlin sources. You can write the names by hand, use javap (below) to check signatures, or skip naming rules entirely with RegisterNatives.
Building the native library
On Windows with clang (the Visual Studio LLVM toolset, or a standalone LLVM install):
clang -shared -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -o nativemath.dll nativemath.c
With MSVC, from a "x64 Native Tools Command Prompt" (or after running vcvars64.bat):
cl /nologo /LD /I"%JAVA_HOME%\include" /I"%JAVA_HOME%\include\win32" nativemath.c /Fe:nativemath.dll
jni.h is in $JAVA_HOME/include, and it includes a platform-specific jni_md.h from the win32, linux or darwin subdirectory. Both commands also produce a nativemath.lib import library, which you can ignore.
On Linux and macOS:
# Linux
gcc -shared -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" -o libnativemath.so nativemath.c
# macOS
clang -shared -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin" -o libnativemath.dylib nativemath.c
The library must match the JVM's architecture: a 64-bit x64 JVM can't load a 32-bit or an ARM64 DLL.
Compile the Kotlin code and run it, pointing java.library.path at the directory with the library:
kotlinc Hello.kt -include-runtime -d app.jar
java --enable-native-access=ALL-UNNAMED -Djava.library.path=. -jar app.jar
42
Hello, Kotlin, from C!
Loading libraries and native access
System.loadLibrary("nativemath") takes a platform-independent name. The JVM turns it into nativemath.dll, libnativemath.so or libnativemath.dylib (System.mapLibraryName does the same) and searches the directories in the java.library.path system property. Its default is PATH on Windows and LD_LIBRARY_PATH plus system directories on Linux.
System.load(path) takes an absolute path to the file instead, which is handy when you ship the library inside your jar, extract it to a temporary directory at startup and load it from there. That's what libraries like SQLite JDBC and Netty do.
If the library isn't found, you get an UnsatisfiedLinkError from loadLibrary:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hashing in java.library.path: .
at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2285)
at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:822)
at java.base/java.lang.System.loadLibrary(System.java:1686)
at demo.Hashing.main(Hashing.kt:9)
If the library loads but a function is missing (a typo in the C name, a missing JNIEXPORT, or C++ name mangling because you forgot extern "C"), the error comes later, on the first call:
42
Exception in thread "main" java.lang.UnsatisfiedLinkError: 'java.lang.String demo.NativeMath.greet(java.lang.String)'
at demo.NativeMath.greet(Native Method)
at demo.HelloKt.main(Hello.kt:14)
The restricted method warning
Since JDK 24 (JEP 472) loading a native library is a restricted operation. Without extra flags you get this on stderr:
WARNING: A restricted method in java.lang.System has been called
WARNING: java.lang.System::loadLibrary has been called by demo.NativeMath in an unnamed module (file:/.../hello.jar)
WARNING: Use --enable-native-access=ALL-UNNAMED to avoid a warning for callers in this module
WARNING: Restricted methods will be blocked in a future release unless native access is enabled
The program still works. To acknowledge that you use native code on purpose:
- pass
--enable-native-access=ALL-UNNAMEDtojava(code on the classpath is in the unnamed module), or--enable-native-access=my.modulefor a named module - or, for an executable jar, add
Enable-Native-Access: ALL-UNNAMEDto the jar's manifest
The same applies to the FFM API. A future JDK will turn the warning into an error, so add the flag now.
Strings
jstring is a reference to a JVM String, not a C string. You convert it:
GetStringUTFCharsreturns a NUL-terminatedconst char *in modified UTF-8, which you must release withReleaseStringUTFChars.NewStringUTFcreates a JVM string from modified UTF-8.
Modified UTF-8 is the same as UTF-8 for ASCII and most text, with two differences: the character U+0000 is encoded as two bytes (so a C string never contains an embedded NUL), and characters outside the Basic Multilingual Plane, like emoji, are encoded as two 3-byte surrogates instead of one 4-byte sequence. If you pass such strings to a C library that expects real UTF-8, convert them in Kotlin first with s.encodeToByteArray() and pass a ByteArray, or use GetStringChars to get UTF-16. See Unicode and encodings.
Arrays
Primitive arrays have a family of functions per element type:
package demo
object NativeArrays {
init { System.loadLibrary("arrays") }
external fun sum(values: IntArray): Long
external fun scale(values: DoubleArray, factor: Double) // modifies in place
external fun squares(n: Int): IntArray
}
fun main() {
println(NativeArrays.sum(intArrayOf(1, 2, 3, 4, 5)))
val data = doubleArrayOf(1.0, 2.5, 4.0)
NativeArrays.scale(data, 2.0)
println(data.contentToString())
println(NativeArrays.squares(6).contentToString())
}
#include <jni.h>
#include <stdlib.h>
JNIEXPORT jlong JNICALL
Java_demo_NativeArrays_sum(JNIEnv *env, jobject self, jintArray values) {
jsize n = (*env)->GetArrayLength(env, values);
jint *elems = (*env)->GetIntArrayElements(env, values, NULL);
if (elems == NULL) return 0;
jlong total = 0;
for (jsize i = 0; i < n; i++) total += elems[i];
/* JNI_ABORT: we didn't change anything, don't copy back */
(*env)->ReleaseIntArrayElements(env, values, elems, JNI_ABORT);
return total;
}
JNIEXPORT void JNICALL
Java_demo_NativeArrays_scale(JNIEnv *env, jobject self, jdoubleArray values, jdouble factor) {
jsize n = (*env)->GetArrayLength(env, values);
jdouble *elems = (*env)->GetDoubleArrayElements(env, values, NULL);
if (elems == NULL) return;
for (jsize i = 0; i < n; i++) elems[i] *= factor;
/* 0: copy changes back (if it was a copy) and free the buffer */
(*env)->ReleaseDoubleArrayElements(env, values, elems, 0);
}
JNIEXPORT jintArray JNICALL
Java_demo_NativeArrays_squares(JNIEnv *env, jobject self, jint n) {
jintArray result = (*env)->NewIntArray(env, n);
if (result == NULL) return NULL;
jint *tmp = malloc(sizeof(jint) * n);
for (jint i = 0; i < n; i++) tmp[i] = i * i;
(*env)->SetIntArrayRegion(env, result, 0, n, tmp);
free(tmp);
return result;
}
15
[2.0, 5.0, 8.0]
[0, 1, 4, 9, 16, 25]
The garbage collector can move arrays, so Get<Type>ArrayElements either pins the array or returns a copy. Every Get needs a matching Release, and the last argument of Release says what to do with the buffer:
0: copy back the changes and free the bufferJNI_COMMIT: copy back but keep the bufferJNI_ABORT: free the buffer without copying back (use it when you only read)
Other options:
Get/Set<Type>ArrayRegioncopies a range into or out of your own buffer. It's the simplest choice for small arrays.GetPrimitiveArrayCriticalgives the most direct access, usually without copying, but betweenGetandReleaseyou must not call other JNI functions, block or take long, because the GC may be held up.
For large data shared between Kotlin and C, a direct java.nio.ByteBuffer (ByteBuffer.allocateDirect) lives outside the Java heap and never moves. C gets its address with GetDirectBufferAddress.
Kotlin objects, callbacks and exceptions
Native code can read fields, call methods and create objects. To do it, it looks up the class, then a field or method by name and type signature. Signatures use the codes from the table above: (ILjava/lang/String;)V is a method that takes an Int and a String and returns Unit.
You don't have to work signatures out by hand. javap -s prints them for compiled classes:
package demo
data class Point(val x: Int, val y: Int)
fun interface WordListener {
fun onWord(index: Int, word: String)
}
object Native {
init { System.loadLibrary("callbacks") }
external fun splitWords(text: String, listener: WordListener): Int
external fun lengthSquared(p: Point): Int
external fun midpoint(a: Point, b: Point): Point
external fun divide(a: Int, b: Int): Int
}
fun main() {
val count = Native.splitWords("the quick brown fox") { i, w -> println("$i: $w") }
println("words: $count")
println(Native.lengthSquared(Point(3, 4)))
println(Native.midpoint(Point(0, 0), Point(10, 4)))
println(Native.divide(10, 3))
try {
Native.divide(1, 0)
} catch (e: ArithmeticException) {
println("caught: $e")
}
try {
Native.splitWords("a b c") { i, w ->
if (w == "b") error("listener failed on '$w'")
println("$i: $w")
}
} catch (e: IllegalStateException) {
println("caught: ${e.message}")
}
}
$ javap -s -cp c.jar demo.WordListener demo.Point
Compiled from "Callbacks.kt"
public interface demo.WordListener {
public abstract void onWord(int, java.lang.String);
descriptor: (ILjava/lang/String;)V
}
Compiled from "Callbacks.kt"
public final class demo.Point {
public demo.Point(int, int);
descriptor: (II)V
public final int getX();
descriptor: ()I
public final int getY();
descriptor: ()I
...
The C side:
#include <jni.h>
#include <string.h>
JNIEXPORT jint JNICALL
Java_demo_Native_splitWords(JNIEnv *env, jobject self, jstring text, jobject listener) {
jclass cls = (*env)->GetObjectClass(env, listener);
jmethodID onWord = (*env)->GetMethodID(env, cls, "onWord", "(ILjava/lang/String;)V");
if (onWord == NULL) return -1; /* NoSuchMethodError is pending */
const char *s = (*env)->GetStringUTFChars(env, text, NULL);
if (s == NULL) return -1;
char buf[256];
int count = 0;
const char *p = s;
while (*p) {
while (*p == ' ') p++;
if (!*p) break;
size_t len = strcspn(p, " ");
if (len >= sizeof buf) len = sizeof buf - 1;
memcpy(buf, p, len);
buf[len] = 0;
p += len;
jstring word = (*env)->NewStringUTF(env, buf);
(*env)->CallVoidMethod(env, listener, onWord, count, word);
(*env)->DeleteLocalRef(env, word);
if ((*env)->ExceptionCheck(env)) break; /* callback threw: stop */
count++;
}
(*env)->ReleaseStringUTFChars(env, text, s);
return count;
}
JNIEXPORT jint JNICALL
Java_demo_Native_lengthSquared(JNIEnv *env, jobject self, jobject p) {
jclass cls = (*env)->GetObjectClass(env, p);
jfieldID fx = (*env)->GetFieldID(env, cls, "x", "I");
jfieldID fy = (*env)->GetFieldID(env, cls, "y", "I");
jint x = (*env)->GetIntField(env, p, fx);
jint y = (*env)->GetIntField(env, p, fy);
return x * x + y * y;
}
JNIEXPORT jobject JNICALL
Java_demo_Native_midpoint(JNIEnv *env, jobject self, jobject a, jobject b) {
jclass cls = (*env)->FindClass(env, "demo/Point");
if (cls == NULL) return NULL;
jmethodID getX = (*env)->GetMethodID(env, cls, "getX", "()I");
jmethodID getY = (*env)->GetMethodID(env, cls, "getY", "()I");
jmethodID ctor = (*env)->GetMethodID(env, cls, "<init>", "(II)V");
jint x = ((*env)->CallIntMethod(env, a, getX) + (*env)->CallIntMethod(env, b, getX)) / 2;
jint y = ((*env)->CallIntMethod(env, a, getY) + (*env)->CallIntMethod(env, b, getY)) / 2;
return (*env)->NewObject(env, cls, ctor, x, y);
}
JNIEXPORT jint JNICALL
Java_demo_Native_divide(JNIEnv *env, jobject self, jint a, jint b) {
if (b == 0) {
jclass ex = (*env)->FindClass(env, "java/lang/ArithmeticException");
if (ex != NULL) (*env)->ThrowNew(env, ex, "division by zero in C");
return 0; /* return value is ignored, the exception is thrown on return */
}
return a / b;
}
0: the
1: quick
2: brown
3: fox
words: 4
25
Point(x=5, y=2)
3
caught: java.lang.ArithmeticException: division by zero in C
0: a
caught: listener failed on 'b'
Things to notice:
Kotlin properties. val x: Int compiles to a private field x and a getter getX(). JNI ignores private, so GetFieldID(cls, "x", "I") works, but calling the getter (midpoint does) is more robust: it keeps working if the property gets a custom getter or is computed. Constructors are always named <init>.
Callbacks. A Kotlin lambda passed where a fun interface is expected becomes an object implementing it, so C calls onWord like any other method. A fun interface gives you a clean, predictable signature. A plain function type (Int, String) -> Unit would work too, but C would have to call the erased invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; and box the Int.
Exceptions are not C++ exceptions. ThrowNew only marks an exception as pending. The C function keeps running, and the exception is thrown in Kotlin when the function returns. The same happens when a callback throws: CallVoidMethod returns normally with a pending exception. While an exception is pending, you may only call a few cleanup functions (release strings and arrays, delete references), so check ExceptionCheck after every call into the JVM and return quickly. Use ExceptionClear if C handles the error itself.
Lookups are slow. FindClass, GetMethodID and GetFieldID do string lookups. In real code, cache method and field IDs (they stay valid as long as the class is loaded), for example in JNI_OnLoad. Cached jclass values must be global references (see below).
Native handles and AutoCloseable
A common JNI pattern: C allocates a struct, Kotlin stores the pointer in a Long, and every native call passes it back. Wrap it in a class that implements AutoCloseable so callers can free it with use:
package demo
class NativeBuffer(capacity: Int) : AutoCloseable {
private var handle: Long = alloc(capacity) // pointer to a C struct
fun append(s: String) {
check(handle != 0L) { "buffer is closed" }
append(handle, s)
}
override fun toString(): String = if (handle == 0L) "<closed>" else contents(handle)
override fun close() {
if (handle != 0L) {
free(handle)
handle = 0L
}
}
companion object {
init { System.loadLibrary("buffer") }
@JvmStatic private external fun alloc(capacity: Int): Long
@JvmStatic private external fun free(handle: Long)
@JvmStatic private external fun append(handle: Long, s: String)
@JvmStatic private external fun contents(handle: Long): String
}
}
fun main() {
val text = NativeBuffer(64).use { buf ->
buf.append("native ")
buf.append("memory")
buf.toString()
}
println(text)
val buf = NativeBuffer(8)
buf.close()
println(buf)
try {
buf.append("x")
} catch (e: IllegalStateException) {
println("caught: ${e.message}")
}
}
#include <jni.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
size_t len, cap;
char *data;
} Buffer;
JNIEXPORT jlong JNICALL
Java_demo_NativeBuffer_alloc(JNIEnv *env, jclass cls, jint capacity) {
Buffer *b = malloc(sizeof(Buffer));
b->len = 0;
b->cap = capacity;
b->data = malloc(capacity + 1);
b->data[0] = 0;
return (jlong)(intptr_t)b;
}
JNIEXPORT void JNICALL
Java_demo_NativeBuffer_free(JNIEnv *env, jclass cls, jlong handle) {
Buffer *b = (Buffer *)(intptr_t)handle;
free(b->data);
free(b);
}
JNIEXPORT void JNICALL
Java_demo_NativeBuffer_append(JNIEnv *env, jclass cls, jlong handle, jstring s) {
Buffer *b = (Buffer *)(intptr_t)handle;
const char *utf = (*env)->GetStringUTFChars(env, s, NULL);
if (utf == NULL) return;
size_t n = strlen(utf);
if (b->len + n > b->cap) {
b->cap = (b->len + n) * 2;
b->data = realloc(b->data, b->cap + 1);
}
memcpy(b->data + b->len, utf, n + 1);
b->len += n;
(*env)->ReleaseStringUTFChars(env, s, utf);
}
JNIEXPORT jstring JNICALL
Java_demo_NativeBuffer_contents(JNIEnv *env, jclass cls, jlong handle) {
Buffer *b = (Buffer *)(intptr_t)handle;
return (*env)->NewStringUTF(env, b->data);
}
native memory
<closed>
caught: buffer is closed
@JvmStatic on a companion object member makes the compiler put a real static native method on NativeBuffer itself, so the C name is Java_demo_NativeBuffer_alloc and the second parameter is a jclass. Without @JvmStatic the native method would be on the NativeBuffer$Companion class (Java_demo_NativeBuffer_00024Companion_alloc, $ is escaped as _00024).
Keeping the native functions private and checking the handle in Kotlin matters: C code that gets a stale or zero pointer doesn't throw an exception, it crashes the whole JVM. The garbage collector knows nothing about memory allocated with malloc, so always free it explicitly (see use and Closeable). If you want a safety net for callers who forget, register the cleanup with java.lang.ref.Cleaner, never with finalize().
RegisterNatives and JNI_OnLoad
If a library exports a function named JNI_OnLoad, the JVM calls it right after loading the library. It's the place to cache class and method IDs and to bind native methods explicitly with RegisterNatives, which avoids the Java_... naming rules altogether. This example also builds with MSVC instead of clang:
@file:JvmName("Hashing")
package demo
external fun fnv1a(data: ByteArray): Int // bound by name
external fun crc_32(data: ByteArray): Long // underscore in name, bound by name
external fun popcount(x: Long): Int // bound with RegisterNatives
fun main() {
System.loadLibrary("hashing")
val bytes = "hello".encodeToByteArray()
println("fnv1a: %08x".format(fnv1a(bytes)))
println("crc32: %08x".format(crc_32(bytes)))
println("expected: %08x".format(java.util.zip.CRC32().apply { update(bytes) }.value))
println("popcount: ${popcount(0xFFL)}")
}
#include <jni.h>
#include <stdint.h>
JNIEXPORT jint JNICALL
Java_demo_Hashing_fnv1a(JNIEnv *env, jclass cls, jbyteArray data) {
jsize n = (*env)->GetArrayLength(env, data);
jbyte *p = (*env)->GetPrimitiveArrayCritical(env, data, NULL);
if (p == NULL) return 0;
uint32_t h = 2166136261u;
for (jsize i = 0; i < n; i++) {
h ^= (uint8_t)p[i];
h *= 16777619u;
}
(*env)->ReleasePrimitiveArrayCritical(env, data, p, JNI_ABORT);
return (jint)h;
}
/* "_" in a Kotlin name becomes "_1" in the C name */
JNIEXPORT jlong JNICALL
Java_demo_Hashing_crc_132(JNIEnv *env, jclass cls, jbyteArray data) {
jsize n = (*env)->GetArrayLength(env, data);
jbyte *p = (*env)->GetPrimitiveArrayCritical(env, data, NULL);
if (p == NULL) return 0;
uint32_t crc = 0xFFFFFFFFu;
for (jsize i = 0; i < n; i++) {
crc ^= (uint8_t)p[i];
for (int k = 0; k < 8; k++) crc = (crc >> 1) ^ (0xEDB88320u & (0 - (crc & 1)));
}
(*env)->ReleasePrimitiveArrayCritical(env, data, p, JNI_ABORT);
return (jlong)(crc ^ 0xFFFFFFFFu);
}
/* any name, not exported: registered in JNI_OnLoad */
static jint popcount_impl(JNIEnv *env, jclass cls, jlong x) {
uint64_t v = (uint64_t)x;
jint n = 0;
while (v) { v &= v - 1; n++; }
return n;
}
static JNINativeMethod methods[] = {
{ "popcount", "(J)I", (void *)popcount_impl },
};
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env;
if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_21) != JNI_OK) return JNI_ERR;
jclass cls = (*env)->FindClass(env, "demo/Hashing");
if (cls == NULL) return JNI_ERR;
if ((*env)->RegisterNatives(env, cls, methods, 1) != 0) return JNI_ERR;
return JNI_VERSION_21;
}
cl /nologo /LD /W3 /I"%JAVA_HOME%\include" /I"%JAVA_HOME%\include\win32" hashing.c /Fe:hashing.dll
java --enable-native-access=ALL-UNNAMED -Djava.library.path=. -cp "hs.jar;kotlin-stdlib.jar" demo.Hashing
fnv1a: 4f9f2cab
crc32: 3610a686
expected: 3610a686
popcount: 8
JNI_OnLoad returns the JNI version the library needs. JNI_VERSION_21 requires JDK 21 or newer; use JNI_VERSION_1_8 if the library must load on older JVMs.
Threads and references
A few rules that cause most JNI crashes:
JNIEnv is per thread. Never store env in a global variable and use it from another thread. Store the JavaVM * instead (from JNI_OnLoad or GetJavaVM) and call GetEnv to get the current thread's JNIEnv.
Native threads must attach. A thread created by C code (pthread_create, CreateThread, a C++ std::thread) can't call into the JVM until it calls (*vm)->AttachCurrentThread(vm, (void **)&env, NULL), and it must call DetachCurrentThread before it exits. Attached threads appear as normal Java threads in thread dumps.
Local references die when the native function returns. Every jobject, jstring, jclass that a JNI function returns is a local reference, valid only in the current native call on the current thread. To keep an object (a callback listener, a cached jclass) across calls, make a global reference with NewGlobalRef and free it with DeleteGlobalRef when done. A forgotten global reference is a memory leak the GC can't fix.
Local references are limited. The JVM guarantees room for 16 local references per call (more with EnsureLocalCapacity). A loop that creates objects should delete each one with DeleteLocalRef, as splitWords above does, or use PushLocalFrame/PopLocalFrame.
Debug with -Xcheck:jni. Running java -Xcheck:jni ... makes the JVM validate JNI calls and print warnings for things like calling JNI functions with an exception pending or passing a wrong reference. It's slow, so use it in development and tests only.
The modern alternative: the FFM API
The Foreign Function & Memory API in java.lang.foreign became final in JDK 22 (JEP 454). It calls native functions directly from Kotlin, with no C glue code, no jni.h and no special function names. If you just want to call an existing C library, use it instead of JNI.
The library is plain C:
/* plain C: no jni.h, no Java_ names */
#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
EXPORT int add(int a, int b) { return a + b; }
EXPORT double average(const double *values, int n) {
double sum = 0;
for (int i = 0; i < n; i++) sum += values[i];
return n > 0 ? sum / n : 0;
}
clang -shared -o mathlib.dll mathlib.c
And the Kotlin code describes each function's signature with a FunctionDescriptor and gets a MethodHandle for it:
import java.lang.foreign.Arena
import java.lang.foreign.FunctionDescriptor
import java.lang.foreign.Linker
import java.lang.foreign.SymbolLookup
import java.lang.foreign.ValueLayout.ADDRESS
import java.lang.foreign.ValueLayout.JAVA_DOUBLE
import java.lang.foreign.ValueLayout.JAVA_INT
import java.lang.foreign.ValueLayout.JAVA_LONG
import java.nio.file.Path
fun main() {
val linker = Linker.nativeLinker()
// 1. a function from the C standard library
val strlen = linker.downcallHandle(
linker.defaultLookup().findOrThrow("strlen"),
FunctionDescriptor.of(JAVA_LONG, ADDRESS),
)
Arena.ofConfined().use { arena ->
val cString = arena.allocateFrom("Hello, FFM!") // NUL-terminated UTF-8 copy
val len = strlen.invokeExact(cString) as Long
println("strlen = $len")
// 2. functions from our own library
val lib = SymbolLookup.libraryLookup(Path.of(System.mapLibraryName("mathlib")).toAbsolutePath(), arena)
val add = linker.downcallHandle(
lib.findOrThrow("add"),
FunctionDescriptor.of(JAVA_INT, JAVA_INT, JAVA_INT),
)
val average = linker.downcallHandle(
lib.findOrThrow("average"),
FunctionDescriptor.of(JAVA_DOUBLE, ADDRESS, JAVA_INT),
)
println("add = ${add.invokeExact(2, 40) as Int}")
val values = doubleArrayOf(1.0, 2.0, 3.0, 10.0)
val nativeValues = arena.allocateFrom(JAVA_DOUBLE, *values) // copy to off-heap memory
println("average = ${average.invokeExact(nativeValues, values.size) as Double}")
} // the arena frees the memory and unloads the library
}
strlen = 11
add = 42
average = 4.0
The pieces:
Linker.nativeLinker()knows the platform's C calling convention.defaultLookup()finds functions in the C standard library.SymbolLookup.libraryLookup(path, arena)loads any shared library;SymbolLookup.loaderLookup()finds symbols in libraries loaded withSystem.loadLibrary.FunctionDescriptor.of(returnLayout, argLayouts...)describes the C signature.JAVA_INTis a Cint,JAVA_LONGa 64-bit integer (size_ton 64-bit platforms),ADDRESSa pointer. UseofVoid(...)forvoidfunctions.- An
Arenaowns native memory.allocateFromcopies a string or an array into native memory, and closing the arena frees all of it. Kotlin'suseworks becauseArenaisAutoCloseable.Arena.ofConfined()is usable from one thread,Arena.ofShared()from many,Arena.global()never frees, andArena.ofAuto()is freed by the GC. invokeExactis a signature-polymorphic method: Kotlin compiles the call using the argument types you pass and the type you cast the result to (as Long). They must match the descriptor exactly, otherwise you get aWrongMethodTypeException. Passvalues.size(anInt) forJAVA_INT, and4LforJAVA_LONG.
Native memory accessed through a MemorySegment is bounds-checked, and using it after its arena is closed throws IllegalStateException instead of crashing.
Callbacks with upcall stubs
C functions that take function pointers can call Kotlin code too. upcallStub turns a MethodHandle into a C function pointer. Here the C library's qsort sorts native memory using a Kotlin comparator:
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.ADDRESS
import java.lang.foreign.ValueLayout.JAVA_INT
import java.lang.foreign.ValueLayout.JAVA_LONG
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
object Callbacks {
// C signature: int compar(const void *a, const void *b)
@JvmStatic
fun compareInts(a: MemorySegment, b: MemorySegment): Int {
val x = a.reinterpret(4).get(JAVA_INT, 0)
val y = b.reinterpret(4).get(JAVA_INT, 0)
return x.compareTo(y)
}
}
fun main() {
val linker = Linker.nativeLinker()
val qsort = linker.downcallHandle(
linker.defaultLookup().findOrThrow("qsort"),
FunctionDescriptor.ofVoid(ADDRESS, JAVA_LONG, JAVA_LONG, ADDRESS),
)
val compareHandle = MethodHandles.lookup().findStatic(
Callbacks::class.java, "compareInts",
MethodType.methodType(Int::class.java, MemorySegment::class.java, MemorySegment::class.java),
)
Arena.ofConfined().use { arena ->
val comparePtr = linker.upcallStub(
compareHandle,
FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS),
arena,
)
val input = intArrayOf(42, 7, 19, 3, 88, 1)
val array = arena.allocateFrom(JAVA_INT, *input)
qsort.invokeExact(array, input.size.toLong(), 4L, comparePtr)
println(array.toArray(JAVA_INT).contentToString())
}
}
[1, 3, 7, 19, 42, 88]
Pointers that come from C (the a and b arguments) are zero-length segments, because the JVM doesn't know how big the memory behind them is. reinterpret(4) declares the size; it's a restricted method, which is one more reason to run with --enable-native-access.
For big C APIs, writing descriptors by hand gets tedious. The jextract tool reads C header files and generates the Java bindings (strlen(MemorySegment), struct layouts, constants), which you can call from Kotlin like any Java library.
JNI or FFM?
| JNI | FFM API | |
|---|---|---|
| Available since | Java 1.1 | JDK 22 (preview from 19) |
| Glue code | C code for every function | none, written in Kotlin |
| Calls existing C libraries | through a wrapper you write | directly |
| Works with JVM objects in C | yes | no, only native memory |
| Memory safety | a bad pointer crashes the JVM | bounds and lifetime checks |
| Android | yes (NDK) | no |
Use FFM for calling C libraries on JDK 22+. Use JNI when you target Android or older JVMs, when native code must work with JVM objects or attach its own threads to the JVM, or when you maintain an existing JNI library.
Two more options: JNA (Java Native Access) is a long-standing library that, like FFM, calls C functions without glue code; it's slower but runs on any JVM. Kotlin/Native compiles Kotlin to native code and imports C headers with its cinterop tool, with no JVM involved at all.
Common mistakes
Wrong function name. A typo in Java_demo_NativeMath_greet, a missing JNIEXPORT, or C++ code without extern "C" (so the name is mangled) all give an UnsatisfiedLinkError on the first call. Remember that a Kotlin object's methods aren't static, top-level functions live in the ...Kt class, and companion members need @JvmStatic to end up on the outer class.
Forgetting to release. Every GetStringUTFChars and Get<Type>ArrayElements needs a matching Release, on every path including errors, or memory leaks (or arrays stay pinned).
Ignoring pending exceptions. After a JNI call that can throw (CallVoidMethod, NewStringUTF, FindClass), check ExceptionCheck or the return value before doing anything else.
Caching local references. Storing a jclass or jobject in a static variable without NewGlobalRef works in quick tests and crashes later, after the GC runs.
Assuming JNI is fast. Each JNI call costs much more than a normal method call, and copying arrays and strings adds more. Calling C for a tiny function in a loop is usually slower than plain Kotlin. Cross the boundary rarely and do a lot of work each time, and measure (see Benchmarks).
Shipping one binary. A .dll doesn't load on Linux or macOS, and an x64 library doesn't load on ARM64. Build the library for every platform you support and pick the right file at runtime, using System.getProperty("os.name") and System.getProperty("os.arch").
Summary
- Declare native functions with
external. Load the library withSystem.loadLibrary(searchesjava.library.path) orSystem.load(absolute path) before the first call. - The C function name is
Java_<package>_<Class>_<method>with_escaped as_1. Top-level functions belong to theFileKtclass, companion members need@JvmStatic.RegisterNativesinJNI_OnLoadavoids the naming rules. - Build with
clang -sharedorcl /LDon Windows,gcc -shared -fPICon Linux, including$JAVA_HOME/includeand its platform subdirectory. - On JDK 24+ run with
--enable-native-access=ALL-UNNAMED(or theEnable-Native-Accessmanifest attribute) to avoid the restricted method warning. - Convert strings and arrays with the
Get.../Release...pairs, look up fields and methods by name and signature (javap -sprints them), and check for pending exceptions after calling into the JVM. - Hide native pointers in an
AutoCloseableclass with privateexternalfunctions; use global references for objects kept across calls and attach native threads before using JNI. - For calling C libraries on JDK 22+, prefer the FFM API (
java.lang.foreign):Linker,FunctionDescriptor,ArenaandMemorySegment, with no C glue code.