JNI: GetStaticMethodID method called

I am writing some code to get a spawned thread to call a Java static method from C ++.

The bits that call the method work fine if placed in a native call from Java, but not from a thread with JNIEnv attached.

I installed JavaVM * as follows:

jint JNI_OnLoad(JavaVM* jvm, void* reserved) { LOGI("Setting Java Virtual Machine"); ThreadJNIEnvironment::javaVM = jvm; return JNI_VERSION_1_6; } 

It is caused.

Then I create another thread and from this thread I do the following:

 JNIEnv* env; jint ret = ThreadJNIEnvironment::javaVM->AttachCurrentThread(&env, NULL); LOGI("AttachCurrentThread returned %d", ret); jclass interfaceClass = env->FindClass("com/ecmsys/mcb/model/McbInterface"); jmethodID testMethod = env->GetStaticMethodID(interfaceClass, "Test", "()V"); env->CallStaticVoidMethod(interfaceClass, testMethod); 

AttachCurrentThread returns 0.

GetStaticMethod explodes, although with the following error:

 Fatal signal 11 (SIGSEGV) at 0x0000002c (code=1)..... 

I just don’t see what I did to upset him ... oh wait ... you cannot access Java application classes from the spawned thread without doing some settings ...

 jint JNI_OnLoad(JavaVM* jvm, void* reserved) { LOGI("Setting Java Virtual Machine"); ThreadJNIEnvironment::javaVM = jvm; JNIEnv* env; jvm->AttachCurrentThread(&env, NULL); jclass mcbInterface = env->FindClass("com/ecmsys/mcb/model/McbInterface"); ThreadJNIEnvironment::interfaceClass = env->NewGlobalRef(mcbInterface); return JNI_VERSION_1_6; } 

Then do the following:

 JNIEnv* env; jint ret = ThreadJNIEnvironment::javaVM->AttachCurrentThread(&env, NULL); LOGI("AttachCurrentThread retured %d", ret); if(ThreadJNIEnvironment::interfaceClass) { jmethodID testMethod = env-->GetStaticMethodID(static_cast<jclass>ThreadJNIEnvironment::interfaceClass), "Test", "()V"); env->CallStaticVoidMethod(static_cast<jclass>(ThreadJNIEnvironment::interfaceClass), testMethod); } ThreadJNIEnvironment::javaVM->DetachCurrentThread(); 

You live and study!

+4
source share
1 answer

Check for exceptions after looking at interfaceClass ( env->ExceptionCheck() ) or just check that it is not NULL. Most likely, the class search is not performed.

+4
source

All Articles