Prerequisites:
Third-party ndk packages that support later GCC versions are required. The default Android version is 4.4.3.
Third-party ndk package download (gcc-4.6.3): http://www.crystax.net/en/android/ndk/7
For more information, see this document.
This test shows the following content:
1. Use STD: function and STD: bind to implement the sigslot mechanism;
2. Use the lambda expression of c ++ 11
3. Callback of Java objects in C ++ code
Example Source:
This test example is from a discussion on the Internet. As a result of lambda expressions, the idea of testing in iOS and Android environments is displayed.
Http://stackoverflow.com/questions/12516239/a-simple-signal-for-a-button-in-c
Main code snippets:
Define callback type
typedef std::function<void(const char *)> callback_t;
Define a global callback function pointer to facilitate calls within the genericbutton class. For initialization, see the following code.
callback_t jni_callback;
Export the JNI function. The main function of this function is to internally find the messageme method of the Java class for callback. The messageme callback method uses three methods: calling directly using jnienv; directly calling Lambda callback function; calling in the genericbutton class (using the sigslot_main function, this function is the main method in the original example ).
extern "C" { JNIEXPORT jstring JNICALL Java_com_sigslot_MainActivity_sigSlot( JNIEnv* env, jobject thiz ) { jstring jstr = env->NewStringUTF("This comes from jni(via JNIEnv directly).\n"); jclass clazz = env->FindClass("com/sigslot/MainActivity"); jmethodID messageMe = env->GetMethodID(clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;"); jobject result = env->CallObjectMethod(thiz, messageMe, jstr); jni_callback=[env, thiz, messageMe](const char* info){ LOGI(info); jstring jstr2 = env->NewStringUTF(info); env->CallObjectMethod(thiz, messageMe, jstr2); }; jni_callback("Lambda in std::function (via lambda callback).\n"); sigslot_main(); // call GenericButton's pressButton method. return env->NewStringUTF("sigslot main from JNI C++!"); }}APK package:
Download, install, and test only for interested users. Download link: http://download.csdn.net/detail/dyw/4674834