我调用了一个 native 程序,该程序创建了另一个线程,该线程将自身附加到 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) 在新创建的线程中,当我尝试调用 printAppletConsole 时 JVM 挂起,它卡在 GetObjectClass() 上。这是为什么?
我怀疑是因为我创建了一个新线程,所以我需要访问一个新的 jobject 实例,但我不确定如何......
谢谢!
最佳答案
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);
关于java - JNI - 线程和 jobject 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5460554/