This is way over my head so here we go.
I am setting a function pointer in C++ with an interface Java object which looks like that on the Java side:
Info_t info_t = new Info_t();
info_t.setCallbackTest(new CallbackTest() {
@Override
public void onCallback(int num) {
System.out.println("callback: " + num);
}
});
where CallbackTest()
is the interface with just one method:
public interface CallbackTest {
void onCallback(int num);
}
and setCallbackTest()
refers to the Java native method which is reflected in the C++ side like that:
JNIEnv *gbl_env;
jmethodID gbl_method;
jobject gbl_callback;
void WrapperFunction(int a) {
gbl_env->ExceptionClear();
gbl_env->CallVoidMethod(gbl_callback, gbl_method, a);
if(gbl_env->ExceptionOccurred()) {
gbl_env->ExceptionClear();
}
return;
}
JNIEXPORT void JNICALL Java_apiJNI_Info_1t_1callbackTest_1set(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2) {
Info *arg1 = (Info *) 0;
(void) jenv;
(void) jcls;
(void) jarg1_;
arg1 = *(Info **)&jarg1;
{
jclass clazz;
jmethodID mid;
clazz = jenv->GetObjectClass(jarg2);
mid = jenv->GetMethodID(clazz, "onCallback", "(I)V");
if(mid == 0) {
std::cout << "could not get method id" << std::endl;
return;
}
gbl_env = jenv;
gbl_method = mid;
gbl_callback = jarg2;
}
// here I am setting function pointer to the helper method which invokes the java code
if(arg1) (arg1)->completionCB = WrapperFunction;
}
All of this was written basing on the Implement callback function in JNI using Interface
I have tried calling the onCallback()
method defined in Java on the C++ side and it works (just like in the link above) but now I am trying to set the value on such struct
under C++
typedef void (*callbackFunction)(int);
typedef struct Info
{
callbackFunction completionCB;
void *caller;
} Info_t;
so later on at some point I would like to get the callbackFunction completionCB
back to Java as an object and probably do various stuff with it.
My question is how can I return/map the function pointer behavior from C++ back to the Java object? Basically, I would like to do the same but in the reverse order. I am able to map Java interface onto function pointer now I would like to map function pointer behavior onto Java object.
EDIT: So far I have come up with such getter for it but I am not sure how to proceed
JNIEXPORT jobject JNICALL Java_apiJNI_Info_1t_1callbackTest_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) {
jobject jresult = 0;
Info *arg1 = (Info *) 0;
callbackFunction result;
(void)jenv;
(void)jcls;
(void)jarg1_;
arg1 = *(Info **)&jarg1;
result = ((arg1)->completionCB);
{
jclass clazz = jenv->FindClass("com/CallbackTest");
???
}
???
return ;
}