I have a cpp function pointer:
using MyclassPtr = std::shared_ptr<Myclass>;
using UpdateCallback = std::function<void(const MyclassPtr&)>;
Now in java I have a interface:
public interface UpdateCallback {
void OnDataUpdate(MyClass data);
}
Requirement is that the cpp library should add itself as a listener to the java event. So, cpp will call setUpdateCallback(UpdateCallback) to add itself as a callback to the application events if occured.
JNI Method:
void MyCustomClassJNI::setUpdateCallback(const UpdateCallback & callback)
{.......}
How to get the function pointer from cpp and map it with the interface, so that when application class calls the interface methods, the cpp function callback is invoked??
Please help.
UpdateCallbackthat contains alongmember variable. In your C++ code you can create an instance of that class and set thelongfield to the address of thestd::functioninstance. The JavaOnDataUpdatemethod can then call anativefunction that retrieves thelongfield, turns it back into astd::functionpointer, and calls the function.reinterpret_cast<jlong>(&callback),reinterpret_cast<UpdateCallback*>(java_long_value).void OnDataUpdate(MyClass data);is actually passing down theMyClass dataobject to JNI. Rather than passing down the callback interface pointer, thisdatashould be the meaningful object to your C++ layer.