在 JNI 调用 API 中工作时将对象传递给 C 函数是否安全?
我正在使用 JNI 调用 API 编写一些代码。 AC 程序启动 JVM 并调用它。 JNIenv 指针对于 C 文件来说是全局的。我有许多 C 函数,需要对给定类的 jobobject 执行相同的操作。所以我编写了辅助函数,它接受一个 jobobject 并处理它,返回所需的数据(C 数据类型......例如, int 状态值)。编写 C 辅助函数并将 jobobject 作为参数传递给它们是否安全?
即(一个简单的例子 - 旨在说明问题):
int getStatusValue(jobject jStatus)
{
return (*jenv)->CallIntMethod(jenv,jStatus,statusMethod);
}
int function1()
{
int status;
jobject aObj = (*jenv)->NewObject
(jenv,
aDefinedClass,
aDefinedCtor);
jobject j = (*jenv)->CallObjectMethod
(jenv,
aObj,
aDefinedObjGetMethod)
status = getStatusValue(j);
(*jenv)->DeleteLocalRef(jenv,aObj);
(*jenv)->DeleteLocalRef(jenv,j);
return status;
}
谢谢。
I am coding up something using the JNI Invocation API. A C program starts up a JVM and makes calls into it. The JNIenv pointer is global to the C file. I have numerous C functions which need to perform the same operation on a given class of jobject. So I wrote helper functions which take a jobject and process it, returning the needed data (a C data type...for example, an int status value). Is it safe to write C helper functions and pass jobjects to them as arguments?
i.e. (a simple example - designed to illustrate the question):
int getStatusValue(jobject jStatus)
{
return (*jenv)->CallIntMethod(jenv,jStatus,statusMethod);
}
int function1()
{
int status;
jobject aObj = (*jenv)->NewObject
(jenv,
aDefinedClass,
aDefinedCtor);
jobject j = (*jenv)->CallObjectMethod
(jenv,
aObj,
aDefinedObjGetMethod)
status = getStatusValue(j);
(*jenv)->DeleteLocalRef(jenv,aObj);
(*jenv)->DeleteLocalRef(jenv,j);
return status;
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不熟悉 JNI 的详细信息,但我注意到的一件事是:
这看起来像官方 JNI 代码,并且它采用
jobect
作为参数。如果它适用于 JNI,那么它就没有理由不适用于您的代码。I'm not acquainted with the details of JNI, but once thing I noticed is this:
That looks like the official JNI code and it is taking a
jobect
as a parameter. If it works for JNI, there is no reason it can't work for your code.所有 jni 对象在本机方法返回之前都有效。只要您不在两个 jni 调用之间存储非全局 jni 对象,一切都应该有效。
jni 函数的调用应该像这样工作:
步骤 4 可以包含任何代码,本地引用在步骤 6 之前保持有效,如果之前没有发布过。
如果要在对本机 java 函数的两次调用之间将 jni 对象存储在 c 端,则必须创建全局引用并稍后释放它们。不释放全局引用会导致内存泄漏,因为垃圾收集器无法释放相关的 java 对象。
All jni objects are valid until the native method returns. As long as you dont store non global jni objects between two jni calls everything should work.
The invocation of a jni function should work like this:
The step 4 can contain any code, local references stay valid until step 6 if not release before.
If you want to store jni objects on the c side between two calls to a native java function you have to create global references and release them later. Not releasing a global reference leads to memory leaks as the garbage collector is unable to free the related java objects.