I need to implement callback function in Java using “interface”. I have wrote the application part as MyJavaFunction(int size, m_GetSizeInterface);
MyJavaFunction(int size, m_GetSizeInterface);
m_Ge
#include #include #include class SimpleQueueEvent { public: SimpleQueueEvent(){}; ~SimpleQueueEvent(){}; //for C++ code call int queueEvent(std::function func){ int curTime = time(0) + rand() % 10000; eventMaps.insert(std::map>::value_type(curTime, func)); return curTime; //Call Java method to invoke method, such as //env->FindClass("...."); //jmethodID method = env->FindMethod("onPostQueueEvent"...); //env->InvokeVoidMethod(); //Java code like this.. // private void onPostQueueEvent(final int eventId){ // listener.PostQueueEvent(new Runnable() { // public void run() { // nativeEventFunc(eventId); // } // }); // private static native void nativeEventFunc(int eventId); } void nativeEventFunc(int eventId){ if(eventMaps.find(eventId) != eventMaps.end()){ std::function func = eventMaps.at(eventId); func(); } } private: std::map> eventMaps; };
//and test code is:
SimpleQueueEvent queueEvent; std::function func = [](){ printf("native runnable..\n"); }; int evenId = queueEvent.queueEvent(func); queueEvent.nativeEventFunc(evenId);