title: Is it possible to implement a Java Interface in C or C++ using JNI?
body: <p>Assume a Java library which includes a class, lets call it <code>Foo</code>. This class contains a constructor and two methods:</p>
  
  <pre><code>// constructor
  Foo();
  
  // returns a random int
  public int bar();
  
  // generates a random int "x" and calls integerGenerated(x)
  public void generateInt(IntGeneratorListenerInterface listenerInterface);
  </code></pre>
  
  <p>This assumes a Java interface <code>IntGeneratorListenerInterface</code> with one method:</p>
  
  <pre><code>void integerGenerated(int generatedInt);
  </code></pre>
  
  <p>I'm able to call <code>bar()</code> from native C and C++. Here's a C++ example, assuming a properly initialized <code>JNIEnv</code> <code>env</code>:</p>
  
  <pre><code>// instantiate Foo
  jclass fooClass = env-&gt;FindClass("com/my/package/Foo");
  jmethodID constructorMethodID = env-&gt;GetMethodID(fooClass, "&lt;init&gt;", "()V");
  jobject fooInstance = env-&gt;NewObject(fooClass, constructorMethodID);
  
  // call bar()
  jmethodID barMethodID = env-&gt;GetMethodID(fooClass, "bar", "()I");
  jint result = env-&gt;CallIntMethod(fooInstance, barMethodID);
  printf("%d", result);
  </code></pre>
  
  <p>What I would like to do is implement the interface <code>IntGeneratorInterface</code> from C/C++ such that when I call <code>generateInt()</code> using  similar JNI calls, I can receive the callback in C, like:</p>
  
  <pre><code>void integerGenerated(int x)
  {
      // do something with the int
  }
  </code></pre>
  
  <p><strong>My question:</strong> Is there any way to implement the Java interface in C/C++, such that I can pass something valid to <code>generateInt()</code>, and have <code>integerGenerated()</code> called in C?</p>
  
  <p>I've looked into JNI's <code>RegisterNatives()</code>, but I believe that would require the Java code to declare and call "native" methods (please correct me if I'm wrong), and I do not have the luxury of modifying the existing Java library. Also note that the trivial Java library is just used here to exemplify my question. I realize such simple functionality can be written just as easily natively.</p>