Skip to content

Instantly share code, notes, and snippets.

@Nimrodda
Last active March 8, 2021 09:35
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Nimrodda/f027c8daebe4e3f44fe8 to your computer and use it in GitHub Desktop.
Save Nimrodda/f027c8daebe4e3f44fe8 to your computer and use it in GitHub Desktop.
Raw JNI with async callbacks
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