我一按下逃跑,jvm就崩溃了

时间:2012-06-06 10:59:32

标签: java c multithreading java-native-interface

  

可能重复:
  what is wrong with this call to the java method?

每当按下转义键时,以下C片段都会调用java函数。 C片段的第一个块在不同的线程上执行,第二个块在不同的线程上执行。当我按下转义键时,显示消息escape key pressed,然后jvm崩溃。为什么java函数没有得到叫?

C代码:

    if(called) {// starts on a different thread
    switch(param) {
        case VK_CONTROL:
            printf("Control pressed !\n");
            //(*Env)->CallVoidMethodA(Env,Obj,mid,"11");
            break;
        case VK_SHIFT:
            printf("Shift pressed !\n");
            //(*Env)->CallVoidMethodA(Env,Obj,mid,"10");
            break;
        case VK_ESCAPE:
            printf("Escape pressed !\n");
            JavaVM *jvm;
            JNIEnv *env;
            jmethodID mid;
            env = (*jvm)->AttachCurrentThread(jvm,&env,NULL);
            jclass cls = (*env)->GetObjectClass(env,Obj);
            mid = (*env)->GetMethodID(env,cls,"callBack","(Ljava/lang/String;)V");
            (*env)->CallVoidMethodA(env,Obj,mid,(*env)->NewStringUTF(env,"1B")); // Calling the java function
            break;
        default:
            printf("The default case\n");
            break;
    }}

    void Java_keylogger_TestKeys_initializeJNIVars
     (JNIEnv *env, jobject obj) { // starts on a different thread

      Obj = (*env)->NewGlobalRef(env,obj);
      if(Obj == NULL) {
        printf("Obj is Null\n");
      }
      called = TRUE;
   }

Java代码段:

    public void callBack(String key) {
      String x = KeyEvent.getKeyText(Integer.parseInt(key, 16));
      System.out.println(x);
    }

I have uploaded the complete code with the output here.

1 个答案:

答案 0 :(得分:1)

您需要初始化jvm变量。您可以使用JNI_CreateJavaVM()方法执行此操作。有关详细信息,请参阅此处:http://docs.oracle.com/javase/1.4.2/docs/guide/jni/spec/invocation.html