gogoWebsite

Android JNI programming C++ callback Java functions

Updated to 1 hour ago

Generally, our NDK programming interfaces are used to call C++ in the Java layer, but in fact, the C++ layer can also call Java functions. The implementation method is as follows:

1. Get the class name: jclass cls = env->FindClass

2. Get class method: jmethodID mid = env->GetMethodID

3. Get class member variable: fieldID fid=env->GetFieldID

4. Generate class object: job obj=env->NewObject (jobect can also be passed down from the Java layer)

5. Call class member method: env->CallXXXMethod (XXX is the return value type of Java method)

 

Here is an example:

First, there is Java code. First, a JniTest class is generated, which contains a method of sayingHelloFromJava. The goal we want to achieve is to assign values ​​(String str), two shaping values ​​(int index1, int index2), and a shaping array (int[] intArray), and then print these values ​​in Java.

 

 

Then the code in C++

Through this example, we can basically understand how the C++ layer calls back Java functions. In addition, there is a small trick here. If you don't know what the type of your Java layer is in C++, you can write this type in the native method and then use the javah method to generate the .h file. Just check the corresponding type comments of the .h file to know the result. For example: We want to know how to write the corresponding types of String and shaping arrays. We add a public native void type(String str, int[] arrayInt) method to native

Then generate the corresponding .h file:

Let's pay attention to the "Signature: (Ljava/lang/String;[I)V" in the comment, where Ljava/lang/String;Ljava/lang/String; is the type of String (note that semicolons cannot be lost), and [I is the type corresponding to the shaping array.