Guest User

Untitled

a guest
Sep 29th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. static jclass callbacksClass;
  2. static jobject callbacksInstance;
  3.  
  4. JNIEXPORT void JNICALL Java_com_example_NativeClass_nativeMethod(JNIEnv* env, jclass callingObject, jobject callbacks)
  5. {
  6. // Cache the Java callbacks instance
  7. callbacksInstance = env->NewGlobalRef(callbacks);
  8.  
  9. // Cache the Java callbacks class (in case of interface, this will be the concrete implementation class)
  10. jclass objClass = env->GetObjectClass(callbacks);
  11. // Check for null
  12. if (objClass)
  13. {
  14. callbacksClass = reinterpret_cast<jclass>(env->NewGlobalRef(objClass));
  15. env->DeleteLocalRef(objClass);
  16. }
  17. }
  18.  
  19. // Example of callback lambdas
  20. void callbacksLambdas()
  21. {
  22. [env]() {
  23. // Invoke method called 'void onInitSucceeded()'
  24. jmethodID onSuccess = env->GetMethodID(callbacksClass, "onInitSucceeded", "()V");
  25. // Invoking the callback method on Java side
  26. env->CallVoidMethod(callbacksInstance, onSuccess);
  27. },
  28. // FailureCallback lambda
  29. [env](int errorCode, const std::string& message) {
  30. // Invoke a method called 'void onInitFailed(int, String)'
  31. jmethodID onFailure = env->GetMethodID(callbacksClass, "onInitFailed", "(ILjava/lang/String;)V");
  32. // Prepare method paramters (note that it's not possible to release the jstring since we are returning it to Java side)
  33. jstring msg = env->NewStringUTF(message.c_str());
  34. jint err = errorCode;
  35. // Invoking the callback method on Java side
  36. env->CallVoidMethod(callbacksInstance, onFailure, err, msg);
  37. }
  38. );
  39. }
  40.  
  41. void release()
  42. {
  43. // Release the global references to prevent memory leaks
  44. env->DeleteGlobalRef(callbacksClass);
  45. env->DeleteGlobalRef(callbacksInstance);
  46. }
Add Comment
Please, Sign In to add comment