JNI - 多线程 [英] JNI - multi threads
问题描述
我有一个用于从C调用的Java函数的JNI包装器...我试图从不同的线程调用一些方法,并且在尝试获取JNIEnv指针的新副本时出现错误...我正在使用的代码在下面,并在每种方法中调用:
I have a JNI wrapper for Java functions that are called from C... I'm trying to call some methods from different threads and I get an error when trying to get a new copy of the JNIEnv pointer... the code I'm using is below and is called in each method:
JNIEnv* GetJniEnvHandle(){
ThreadInfo();
JNIEnv *envLoc;
//if(Thread::CurrentThread->IsBackground || Thread::CurrentThread->IsThreadPoolThread)
jint envRes = vm->GetEnv((void**)&envLoc, JNI_VERSION_1_4);
if(envRes == JNI_OK){
if(ThreadId != Thread::CurrentThread->ManagedThreadId)
jint res = vm->AttachCurrentThread((void**)&envLoc, NULL);
}else{
Log("Error obtaining JNIEnv* handle");
}
return envLoc;
}
JVM已经被实例化,这个(以及其他方法)在运行时运行从主/初始线程调用。当我得到envRes的值时,它在子线程中保持-2。
The JVM has already been instantiated and this (and other methods) run when being called from the main/initial thread. When I get a value for envRes it holds a -2 when in a sub-thread.
推荐答案
请参考文档到附加到VM
。
在使用任何JNI之前,您需要至少为每个本机线程调用 AttachCurrentThread()
函数。
用Java创建的线程已经附加。
所以每当 GetEnv
调用失败时,我的例子都会调用 AttachCurrentThread()
你应该没问题。或者确保在创建子线程时将其附加到VM。
You need to call AttachCurrentThread()
for each native thread at least once before you can use any of the JNI functions.
Thread created in Java are already attached.
So I your example whenever the GetEnv
call fails call AttachCurrentThread()
and you should be fine. Or make sure that whenver you create a sub thread you attach it to the VM.
这篇关于JNI - 多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!