Android Java Native Interface (JNI) suggest change

How to call functions in a native library via the JNI interface

The Java Native Interface (JNI) allows you to call native functions from Java code, and vice versa. This example shows how to load and call a native function via JNI, it does not go into accessing Java methods and fields from native code using JNI functions.

Suppose you have a native library named libjniexample.so in the project/libs/<architecture> folder, and you want to call a function from the JNITestJava class inside the com.example.jniexample package.

In the JNITest class, declare the function like this:

public native int testJNIfunction(int a, int b);

In your native code, define the function like this:

#include <jni.h>

JNIEXPORT jint JNICALL Java_com_example_jniexample_JNITest_testJNIfunction(JNIEnv *pEnv, jobject thiz, jint a, jint b)
{
    return a + b;
}

The pEnv argument is a pointer to the JNI environment that you can pass to JNI functions to access methods and fields of Java objects and classes. The thiz pointer is a jobject reference to the Java object that the native method was called on (or the class if it is a static method).

In your Java code, in JNITest, load the library like this:

static{
    System.loadLibrary("jniexample");
}

Note the lib at the start, and the .so at the end of the filename are omitted.

Call the native function from Java like this:

JNITest test = new JNITest();
int c = test.testJNIfunction(3, 4);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents