java - 从 native C 代码(JNI)传递 Java 中的回调函数的多个参数

标签 java android c++ c java-native-interface

下面的代码从 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/

相关文章:

Java相当于python中的bisect

Java-加载资源目录

java - 如何编写找到两点之间最大距离的 O(n^2) 方法

java - Spring MVC Web 应用程序 : application context starts twice

android - 如何知道重复的库是模块还是组?

c++ - 使用区域设置在字符串中查找子字符串

android - 在 CursorTreeAdapter 类的 getChildrenCursor() 方法中异步查询数据库的模式

java - 仅当结果已可用时启动异步任务并在单击按钮时执行操作,否则等待结果然后执行操作

c++ - 如何读取包含多个根元素的 JSON 文件?

c++ - 检查 OSX 是否采用 24 小时制