-1

Possible Duplicate:
what is wrong with this call to the java method?

The following C snippet calls a java function whenever the escape key is pressed. The first block of C snippet executes on a different thread and second block executes on a different thread.When i press the escape key,the message escape key pressed is displayed and then the jvm crashes.Why doesn't the java function get called ?

C Code :

    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 Snippet :

    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.

Community
  • 1
  • 1
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • 2
    the most obvious ones are jvm and env in the switch pointing to nowhere. – josefx Jun 06 '12 at 11:04
  • I have been answering this question here: http://stackoverflow.com/questions/10895826/what-is-wrong-with-this-call-to-the-java-method/10896756#10896756 Why are you posting the same question again???? – maba Jun 07 '12 at 09:20

1 Answers1

1

You need to initialize your jvm variable. You can do this using JNI_CreateJavaVM()method. See here for more information: http://docs.oracle.com/javase/1.4.2/docs/guide/jni/spec/invocation.html

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
  • 1
    and how can i initialize the third argument _(vm_args)_ in this method ? The link you have given in the answer,is too old. The struct `JDK1_1InitArgs` mentioned in the link has been removed from the header file. – Suhail Gupta Jun 06 '12 at 12:38
  • I checked the jni.h in the JDK1.7 and there is the struct `JavaVMInitArgs`. I guess this one replaces the older one. See \include\jni.h in your computer for further details. – Hakan Serce Jun 06 '12 at 12:56