JNI - 线程和jobject的问题

时间:2011-03-28 14:36:16

标签: java c++ dll jvm java-native-interface

我调用了一个本机程序,它创建了另一个自己附加到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);
    }
}

我有一个问题;

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

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

谢谢!

1 个答案:

答案 0 :(得分:7)

m_job = job;

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

JNIEnv* jenv = new JNIEnv();
applet_java_jvm->AttachCurrentThread((void**)jenv,NULL);

应该是:

JNIEnv* jenv = 0:
applet_java_jvm->AttachCurrentThread(&jenv,NULL);

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

JNIEnv* jenv = 0:
applet_java_jvm->AttachCurrentThread((void **) &jenv,NULL);
相关问题