Essential Android Android NDK edit forum

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 in the project/libs/ 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:


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);

Table Of Contents
26 Android NDK
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close