0

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.

4
  • Create an implementation of UpdateCallback that contains a long member variable. In your C++ code you can create an instance of that class and set the long field to the address of the std::function instance. The Java OnDataUpdate method can then call a native function that retrieves the long field, turns it back into a std::function pointer, and calls the function. Commented Nov 28, 2018 at 9:32
  • @Michael: How to get the address of std::function and then turn it back to std::function? Commented Nov 28, 2018 at 11:43
  • reinterpret_cast<jlong>(&callback), reinterpret_cast<UpdateCallback*>(java_long_value). Commented Nov 28, 2018 at 12:06
  • Your void OnDataUpdate(MyClass data); is actually passing down the MyClass data object to JNI. Rather than passing down the callback interface pointer, this data should be the meaningful object to your C++ layer. Commented Nov 29, 2018 at 9:18

1 Answer 1

1

Your void OnDataUpdate(MyClass data); is actually passing down the MyClass data object to JNI.

Rather than passing down the callback interface pointer, probably, MyClass data should be the meaningful object to your C++ layer.

From Java side

// Java code
public class MyCustomClassJNI implements UpdateCallback {

    public native void notifyJni(MyClass data);

    @Override
    void OnDataUpdate(MyClass data) {
        this.notifyJniPeer(data);
    }
}

Then on C++ side, you should have a JNI method like below:

JNIEXPORT void JNICALL
Java_your_package_name_MyCustomClassJNI_notifyJni(JNIEnv *env, jobject myClassData) {
    // read myClassData object. 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Did in a similar fashion as suggested by u & Michael

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.