简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM