Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
Add Comment
Please, Sign In to add comment