下面的代码从 native c 代码调用 java 中的回调函数,传递一些字符串数据作为参数。
原生C层
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(回调处理程序)
@Keep
private void CallbackHandler(String string_data) {
// Some Code
}
除了字符串之外,我还想传递 int 类型数据。我的 java 回调处理程序如下所示。我应该在 native 层中更改什么来支持两个参数。
@Keep
private void CallbackHandler(String string_data, int int_data) {
// Some Code
}
最佳答案
您需要将方法签名从 (Ljava/lang/String;)V
更改为 (Ljava/lang/String;I)V
:
jmethodID statusId = env->GetMethodID(pctx->jniHelperClz, “CallbackHandler”, "(Ljava/lang/String;I)V”);
此外,您使用 DeleteLocalRef()
的方式不正确。此方法用于删除通过 NewLocalRef()
创建的本地引用,但 NewStringUTF()
不会创建它们。 NewStringUTF()
方法在垃圾收集器控制下的 Java 堆中创建 jstring
对象。您不需要手动删除它。
注意:
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.
您需要使用DeleteLocalRef()
立即删除大对象(例如在循环中)。
关于java - 从 native C 代码(JNI)传递 Java 中的回调函数的多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47528981/