-
-
Save sdesalas/41452aedf78c5167fc74734d28256a53 to your computer and use it in GitHub Desktop.
Raw JNI with async callbacks
This file contains hidden or 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
static jclass callbacksClass; | |
static jobject callbacksInstance; | |
JNIEXPORT void JNICALL Java_com_example_NativeClass_nativeMethod(JNIEnv* env, jclass callingObject, jobject callbacks) | |
{ | |
// Cache the Java callbacks instance | |
callbacksInstance = env->NewGlobalRef(callbacks); | |
// Cache the Java callbacks class (in case of interface, this will be the concrete implementation class) | |
jclass objClass = env->GetObjectClass(callbacks); | |
// Check for null | |
if (objClass) | |
{ | |
callbacksClass = reinterpret_cast<jclass>(env->NewGlobalRef(objClass)); | |
env->DeleteLocalRef(objClass); | |
} | |
} | |
// Example of callback lambdas | |
void callbacksLambdas() | |
{ | |
[env]() { | |
// Invoke method called 'void onInitSucceeded()' | |
jmethodID onSuccess = env->GetMethodID(callbacksClass, "onInitSucceeded", "()V"); | |
// Invoking the callback method on Java side | |
env->CallVoidMethod(callbacksInstance, onSuccess); | |
}, | |
// FailureCallback lambda | |
[env](int errorCode, const std::string& message) { | |
// Invoke a method called 'void onInitFailed(int, String)' | |
jmethodID onFailure = env->GetMethodID(callbacksClass, "onInitFailed", "(ILjava/lang/String;)V"); | |
// Prepare method paramters (note that it's not possible to release the jstring since we are returning it to Java side) | |
jstring msg = env->NewStringUTF(message.c_str()); | |
jint err = errorCode; | |
// Invoking the callback method on Java side | |
env->CallVoidMethod(callbacksInstance, onFailure, err, msg); | |
} | |
); | |
} | |
void release() | |
{ | |
// Release the global references to prevent memory leaks | |
env->DeleteGlobalRef(callbacksClass); | |
env->DeleteGlobalRef(callbacksInstance); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment