title: calling java method from c++ using JNI
body: <p>i'm trying to wrap a c++ library for a specific usb device in JAVA.
  the library supports Callback functions to inform the application about the attachment and detachment of usb device to PC.</p>
  
  <p>the call back function must have a specific format like this:</p>
  
  <pre><code>DWORD callbackFunction(void *params);
  </code></pre>
  
  <p>so i implemented a function like this in JNI dll and want to call a function in Java wapper whenever this function is called.</p>
  
  <p>the question is what JNIENV i should use for calling GetObjectClass, GetMethodID and CallVoidMethod from?</p>
  
  <hr>
  
  <p>This is how I initialize my DLL. the "Set(AttachDetach)Callback" methods accept a callback function(first parameter) and a void* parameter(secondparameter) that will be passed to the function when module attach/detach is detected.</p>
  
  <pre><code>JNIEXPORT void JNICALL Java_MyPackage_MyClass_InitializeDLL
  (JNIEnv *env, jobject obj, jobject callback)
  {
        // Storing callback object in global variable.
      callBackObj = callback;
  
      env-&gt;GetJavaVM(&amp;jvm);
  
      MyInstance = new MyClass();
      MyInstance -&gt;SetAttachCallback(AttachCallBack, &amp;callBackObj);
      MyInstance -&gt;SetDetachCallback(DetachCallBack, &amp;callBackObj);
  
        // Testing!
      jclass callBackCls = env-&gt;FindClass("MyPackage/MyClassCallBacks");
      jmethodID mid = env-&gt;GetMethodID(callBackCls, "attach", "(B)V");
      if (!mid)
          return ; /* method not found */
        //This call here works well
      env-&gt;CallVoidMethod(callBackObj, mid, 5);
  }
  </code></pre>
  
  <p>then i set a callback function in DLL for the USB device and it is successfully called when i attach the device.</p>
  
  <p>The code i put in attach callback of the USB device is this:</p>
  
  <pre><code>DWORD CALLBACK AttachCallBack(CallbackParams* params)
  {
      JNIEnv *env;
      jvm-&gt;AttachCurrentThread((void **)&amp;env, NULL);
  
      jclass callBackCls = env-&gt;FindClass("MyPackage/MyClassCallBacks");
      jmethodID mid = env-&gt;GetMethodID(callBackCls, "attach", "(B)V");
      if (!mid)
          return -1; /* method not found */
        // This call fails with an access violation Exception
      env-&gt;CallVoidMethod(*((jobject *)(params-&gt;param)), mid, params-&gt;moduleIndex);
        // This fails the same way too
      env-&gt;CallVoidMethod(callBackObj, mid, 5);
  
      jvm-&gt;DetachCurrentThread();
  
      return 0;
  }
  </code></pre>
  
  <p>Before i use AttachCurrentThread i wasn't able to use JNIENV pointer at all. but now any other use of this pointer is successful instead of the call to CallVoidMethod.
  Do you see what is wrong here?</p>
  
  <p>Let me add that MyPackage.MyClassCallBacks Is an interface that it's method is implemented in another calss namely "callBackClass"</p>