JNI - 线程和jobject的问题

Kai*_*aan 9 c++ java dll java-native-interface jvm

我调用了一个本机程序,它创建了另一个自己附加到JVM的线程.现在我想访问JVM的方法,但它失败了.这是代码:

//
// This is the native function that gets called first. 
// it creates another thread which runs, and also calls the printing-methods in my
// java applet. 
//
JNIEXPORT void JNICALL Java_EIGC_1Applet_app_1native_native_1start(JNIEnv* jenv, jobject job) {

    printAppletConsole(jenv,job,"unused atm");
    // save current java VM;
    // save main applet class;
    // used by main thread
    jenv->GetJavaVM(&applet_java_jvm);
    m_job = job;


    // create the working and start it
    applet_thread_main = new EIGC_Applet_thread(&main);
    applet_thread_main->start();
}


//
// This is the running thread that was created
// This will run and call the printing method in the applet
//
unsigned __stdcall main(void* args) {
    // The JNIEnv
    JNIEnv* jenv = new JNIEnv();

    // attach thread to running JVM
    applet_java_jvm->AttachCurrentThread((void**)jenv,NULL);

    // main running loop
    while (true) {
         Sleep(1000);
         printAppletConsole(jenv,m_job,"unused");
    }

    applet_thread_main->stop();
    return 0;
    }


//
// Calls the "writeConsole()" method in applet which prints "test" in a JTextArea
//
void printAppletConsole(JNIEnv* jenv,jobject job,char* text) {
    jclass cls = jenv->GetObjectClass(job);
    jmethodID mid = jenv->GetMethodID(cls,"writeConsole","()V");
    if (mid==NULL) { 
            printf("Method not found");
    }
    else {
        jenv->CallVoidMethod(job,mid);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个问题;

1)在新创建的线程中,JVM只是在我尝试调用printAppletConsole时挂起,它挂起在GetObjectClass()上.为什么是这样?

我怀疑是因为我创建了一个新线程,我需要访问一个新的jobject实例,但我不确定如何...

谢谢!

Eri*_*rik 7

m_job = job;
Run Code Online (Sandbox Code Playgroud)

这只会保留本地引用,只要您返回java就会无效.您需要进行全局参考NewGlobalRef并存储它.

JNIEnv* jenv = new JNIEnv();
applet_java_jvm->AttachCurrentThread((void**)jenv,NULL);
Run Code Online (Sandbox Code Playgroud)

应该:

JNIEnv* jenv = 0:
applet_java_jvm->AttachCurrentThread(&jenv,NULL);
Run Code Online (Sandbox Code Playgroud)

编辑:对于较旧的JNI版本,使用:

JNIEnv* jenv = 0:
applet_java_jvm->AttachCurrentThread((void **) &jenv,NULL);
Run Code Online (Sandbox Code Playgroud)