Suppose a Java library that includes a class lets you call it Foo . This class contains a constructor and two methods:
// constructor Foo(); // returns a random int public int bar(); // generates a random int "x" and calls integerGenerated(x) public void generateInt(IntGeneratorListenerInterface listenerInterface);
This assumes the Java IntGeneratorListenerInterface interface IntGeneratorListenerInterface one way:
void integerGenerated(int generatedInt);
I can call bar() from native C and C ++. Here's a C ++ example assuming a correctly initialized JNIEnv env :
// instantiate Foo jclass fooClass = env->FindClass("com/my/package/Foo"); jmethodID constructorMethodID = env->GetMethodID(fooClass, "<init>", "()V"); jobject fooInstance = env->NewObject(fooClass, constructorMethodID); // call bar() jmethodID barMethodID = env->GetMethodID(fooClass, "bar", "()I"); jint result = env->CallIntMethod(fooInstance, barMethodID); printf("%d", result);
I would like to implement the IntGeneratorInterface interface from C / C ++, so when I call generateInt() using similar JNI calls, I can get a callback in C, for example:
void integerGenerated(int x) {
My question is: Is there a way to implement the Java interface in C / C ++ so that I can pass something valid for generateInt() and have integerGenerated() called in C?
I looked through JNI RegisterNatives() , but I believe that Java code needs to declare and call the "native" methods (please correct me if I'm wrong), and I have no luxury modifying the existing Java library. Also note that the trivial Java library is used here only to illustrate my question. I understand that such simple functionality can be written just as easily initially.
source share