JNIEnv *env指针不可为多个线程共用,但是java虚拟机的JavaVM指针是整个jvm公用的,我们可以通过JavaVM来得到当前线程的JNIEnv指针.
示例代码:
#include
static JavaVM* g_vm = NULL;
static jclass g_mainActivityClass = NULL;
static jmethodID g_ID = NULL;
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv * env = NULL;
if(g_vm == NULL){
g_vm = vm;
}
if ( (*g_vm)->GetEnv(vm,(void**)&env, JNI_VERSION_1_2) != JNI_OK) {
LOGD("ERROR: GetEnv failed");
return -1;
};
jclass mainActivityClass = (*env)->FindClass(env,"com/ht/htvideodemo/activity/MainActivity");
if( mainActivityClass == NULL){
return -2;
}
g_mainActivityClass = (*env)->NewGlobalRef(env,mainActivityClass);
return JNI_VERSION_1_2;
}
//C函数的回调
}
(*g_vm)->DetachCurrentThread(g_vm); //释放线程,否则会导致内存泄漏