title: C++ calling Java object method: Access Violation
body: <p>I'm trying to implement a Java/C++ binding for a sound streaming class. To keep my example simple, I will reduce it to its seeking method, which is enough to describe my problem:</p>
  
  <pre><code>public abstract class JSoundStream extends SoundStream {
      public abstract void seek(float timeOffset);
  }
  </code></pre>
  
  <p>For testing, I use the following implementation:</p>
  
  <pre><code>@Override public void seek(float timeOffset) {
      System.out.println("seek(" + timeOffset + ")");
  }
  </code></pre>
  
  <p>The <code>seek</code> method is a callback method, delegated to by a native C++ functions that serves as a callback for whatever plays the stream. Picture a media player application with a fast forward function as an example:</p>
  
  <p>"Fast forward" button pressed -> Streaming library invokes C++ callback <code>seek</code> -> Delegate to Java method <code>seek</code></p>
  
  <p><em>Note this is just an example, neither the Event Dispatch Thread nor anything else funky is involved.</em></p>
  
  <p>When an instance of <code>JSoundStream</code> gets created, a native method is called that will save back both the Java VM pointer (<code>JavaVM*</code>) as well as the Java object reference (<code>jobject</code>). I do this because I cannot control when exactly the callback is called, and I know of no way to get the JNI environment or the object <em>live</em> with no Java references whatsoever. So I save back that information at the time of object creation, where I do have the references.</p>
  
  <p>Inside of the C++ <code>seek</code> method, I'm trying to invoke the Java <code>seek</code> method this way:</p>
  
  <pre><code>virtual void OnSeek(float timeOffset) {
      JNIEnv* env;
      jvm-&gt;AttachCurrentThread((void**)&amp;env, NULL);
      env-&gt;CallVoidMethod(binding, m_seek, (jfloat)timeOffset);
  }
  </code></pre>
  
  <p>Where <code>binding</code> is the <code>jobject</code>, <code>jvm</code> the Java VM pointer and <code>m_seek</code> the <code>jmethodID</code> of the <code>seek</code> method I obtained before.</p>
  
  <p>However, that invocation of <code>CallVoidMethod</code> will result in an access violation in <code>jvm.dll</code>. All of the pointers and values are valid for what I can say, and I did make sure the Java object does not get garbage collected. I believe that storing the <code>jobject</code> and / or the Java VM pointer is the source of the problem, but then again I cannot see why, because those values are not changing while the program is running.</p>
  
  <p>Can anybody see a problem in the way I am approaching this? How else - without storing references - would I invoke a Java object method from C++ code?</p>