我正在与另一个更大的 native 框架一起实现一些 JNI 回调( native -> java)功能,并且在框架的回调之一上尝试回调时遇到此错误java.
FATAL Error in native method: Using JNIEnv in non-java thread
这到底是什么意思?什么是 java 线程以及如何在另一个 native 线程中使用 JNI?
最佳答案
Java must be attached到要执行的线程。
The JNI interface pointer (
JNIEnv
) is valid only in the current thread. Should another thread need to access the Java VM, it must first call AttachCurrentThread() to attach itself to the VM and obtain a JNI interface pointer. Once attached to the VM, a native thread works just like an ordinary Java thread running inside a native method.
为此,您必须通过 JNI_OnLoad()
存储指向 JVM 对象的指针。导出或通过使用 (JNIEnv*)java->GetJavaVm(&(JavaVM*)jvm);
实现的 JNI native
调用存储它。
从这里开始,每次需要使用 JNI 时,只需调用以下代码即可附加到当前线程并检索新的 JNIEnv*
指针。
JNIEnv* AttachJava()
{
JavaVMAttachArgs args = {JNI_VERSION_1_2, 0, 0};
JNIEnv* java;
jvm->AttachCurrentThread((void**) &java, &args);
return java;
}
<小时/>
不要保存 JNIEnv*
的实例,除非您确定它们将在同一线程中被引用。
作为documentation states ,在已附加的线程上调用 AttachCurrentThread
是无操作,因此是无害的。
关于java - native 方法中出现 fatal error : Using JNIEnv in non-java thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962972/