为什么jvm崩溃,因为我回调了java函数?

时间:2012-10-04 14:22:59

标签: java c java-native-interface

以下java代码段调用jni函数Java_org_suhail_keylogger_HelperClasses_NativeMethods_unregisterHook

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    jMenuItem1.setEnabled(false);
    jMenuItem2.setEnabled(true);
    try {
       System.loadLibrary("Dll_PKeylogger"); // Load the dll written to listen to the tapping of keys
       nativeMethods.initializeJNIVars(); // called upon the object of a class named NativeMethods
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

NativeMethods (类,其对象用于调用上面的JNI C方法):

public class NativeMethods {

  public native void initializeJNIVars();
  public native void unregisterHook();

  public void displayKeyStrokes() { // FUNCTION THAT IS CALLED BACK FROM JNI C CODE
    System.out.println("Java Message : A Key has been pressed");
  }
}

JNI C方法,由java代码调用:

void Java_org_suhail_keylogger_HelperClasses_NativeMethods_initializeJNIVars
(JNIEnv *env, jobject obj) {
  jclass cls = (*env)->GetObjectClass(env,obj);
  callBackToDeliverKeyStroke = (*env)->GetMethodID(env,cls,"displayKeyStrokes","()V");
  object = (*env)->NewGlobalRef(env,obj);
  if(object == NULL | callBackToDeliverKeyStroke == NULL | cls == NULL) {
     printf("Initialization error...One of the variable is Null\n");
  }
 }

与上述调用java函数的方法相同的模块中的方法

static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
  JNIEnv *Env;
  (*Env)->CallVoidMethod(Env,object,callBackToDeliverKeyStroke); 
  // I have initialized object and callBackToDeliverKeyStroke in the above method
}

当执行到达最后一个执行点时,即上面提到的函数JVM崩溃了。这是为什么 ?我哪里弄错了?

1 个答案:

答案 0 :(得分:5)

JNIEnv *Env;
(*Env)->CallVoidMethod(Env,object,callBackToDeliverKeyStroke);

Env未初始化。