9
我已经调用了一个本地程序,它创建了另一个线程,它将自己附加到JVM。现在我想访问JVM的方法,但是失败了。这里是代码:JNI - 线程和jobject的问题
//
// 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的新实例,但是我不知道如何..
谢谢!
1.所以例如new_job = NewGlobalRef(m_job)在printConsole功能?功能完成后,我必须删除new_job吗? 2.你确定JNIEnv初始化吗?它崩溃,如果我做JNIEnv * jenv = 0,并且编译器也不喜欢&jenv,因为它不是void **指针。谢谢你,先生! – KaiserJohaan 2011-03-28 14:54:42
不,请在'Java_EIGC_1Applet_app_1native_native_1start'中使用'm_job = jenv-> NewGlobalRef(job)'。当你完全使用它时,也调用'jenv-> DeleteGlobalRef(m_job)'。 – Erik 2011-03-28 14:58:36
我明白了。非常感谢! – KaiserJohaan 2011-03-29 07:18:13