简体   繁体   中英

Passing multiple arguments for callback function in java from native c code (JNI)

Below code calls a callback function in java from native c code passing some string data as argument.

Native C layer

jmethodID statusId = env->GetMethodID(pctx->jniHelperClz, "CallbackHandler", "(Ljava/lang/String;)V");
jstring string_data = env->NewStringUTF((const char*)"SOME_STRING_DATA");
env->CallVoidMethod(pctx->jniHelperObj, statusId, string_data);
env->DeleteLocalRef(string_data);

Android / Java (Callback handler)

@Keep
private void CallbackHandler(String string_data) {
    // Some Code
}

Along with string I want to pass a int type data also. My java Callback handler looks like below. What should I change in my native layer to support two arguments.

@Keep
private void CallbackHandler(String string_data, int int_data) {
    // Some Code
}

You need to change method signature from (Ljava/lang/String;)V to (Ljava/lang/String;I)V :

jmethodID statusId = env->GetMethodID(pctx->jniHelperClz, “CallbackHandler”, "(Ljava/lang/String;I)V”);

Also, you use DeleteLocalRef() not proper way. This method used to delete the local references created via NewLocalRef() , but NewStringUTF() not create them. Method NewStringUTF() create jstring object in java heap which under garbage collector control. You don't need to delete this manually.

Take note:

Local references are valid for the duration of a native method call. They are freed automatically after the native method returns. Each local reference costs some amount of Java Virtual Machine resource. Programmers need to make sure that native methods do not excessively allocate local references. Although local references are automatically freed after the native method returns to Java, excessive allocation of local references may cause the VM to run out of memory during the execution of a native method.

You need to use DeleteLocalRef() to immediately delete large objects (for example in loop).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM