Last active
May 6, 2018 11:21
-
-
Save alexcohn/c41d53683efec541e679f847f068fe33 to your computer and use it in GitHub Desktop.
code sample for https://stackoverflow.com/questions/50164786/jni-call-c-method-from-java-using-void-pointers: C++ side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <jni.h> | |
JNIEXPORT void JNICALL | |
Java_com_example_thunks_SomeClass_callback(JNIEnv *env, jobject obj, jint arg1, jlong arg2) | |
{ | |
jclass SomeClass = (*env)->GetObjectClass(env, obj); | |
jfieldID nativeCallback_ID = (*env)->GetFieldID(env, SomeClass, "m_nativeCallback", "J"); // it would be wise to cache this ID | |
void (*callbackPtr)(int, long) = (void (*)(int, long)) (*env)->GetLongField(env, object, nativeCallback_ID); | |
callbackPtr(arg1, arg2); | |
} | |
// the callbacks - may even be result of dlsym() | |
void callback1(int arg1, long arg2) | |
{ | |
… | |
} | |
void callback2(int arg1, long arg2) | |
{ | |
… | |
} | |
// this is not a Java method!! | |
void registerSomeJavaCallback(JNIEnv *env, jobject obj, jlong fpointer) | |
{ | |
// set the chosen callback for an existing object of SomeClass | |
// jclass SomeClass = (*env)->FindClass(env, "com/example/thunks/SomeClass"); // we could find the class by name, too | |
jclass SomeClass = (*env)->GetObjectClass(env, object); | |
jfieldID nativeCallback_ID = (*env)->GetFieldID(env, SomeClass, "m_nativeCallback", "J"); | |
(*env)->SetLongField(env, object, nativeCallback_ID, fpointer); | |
} | |
// example of calling this function: | |
// note that we must use `long long`, not `int` here: | |
registerSomeJavaCallback(theCurrentThreadEnv, someObj, (int64_t)&callback1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment