JNI (Java Native Interface) is a powerful tool that enables Android developers to utilize the NDK and use C++ native code in their applications. This topic describes the usage of Java <-> C++ interface.
How to call a Java method from native code
The Java Native Interface (JNI) allows you to call Java functions from native code. Here is a simple example of how to do it:
JNI method signature to Java type:
L fully-qualified-class ;
So for our example we used (Z)I - which means the function gets a boolean and returns an int.
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:
In your native code, define the function like this:
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:
Utility method in JNI layer
This method will help to get the Java string from C++ string.
This method will help you to convert jbyteArray to char
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0