JNI: native method that spawns threads that need to interact with Java

73 Views Asked by At

I have a C method that is called from a Java process:

extern "C" {
    JNIEXPORT jstring JNICALL Java_bla_bla_bla(JNIEnv *env, jclass java_class, jint param) {
         /* Spawn C threads that are going to call Java methods */
    }
}

The problem is that all what my native method gets from Java is a JNIEnv instance. In order to call AttachCurrentThread(), I need a JavaVM object.

How can I get the JavaVM pointer from my native method?

1

There are 1 best solutions below

0
On BEST ANSWER

One alternative is to cache the JavaVM* you receive in JNI_OnLoad.

Another alternative is to call the GetJavaVM function that is part of the JNIEnv:

JNIEXPORT jstring JNICALL Java_bla_bla_bla(JNIEnv *env, jclass java_class, jint param) {
    JavaVM *jvm;
    if (env->GetJavaVM(&jvm)) {
        // Something went wrong
    }
    // Pass jvm to the new thread