Howto: Callback from C++ to Java, initiated from the Java side (not C++ to JVM function call)?

533 views
Skip to first unread message

vbag...@gmail.com

unread,
Jul 24, 2018, 8:17:58 PM7/24/18
to javacpp
Hello,

I am new to JavaCPP and trying to do a do a callback from C++ to Java. 

I have seen the example in the JavaCPP readme on creating callback functions, but if I understand correctly, it shows how to call a Java function from C++, whereby the JVM is initiated from C++,  using JavaCPP_init(). 

I would like to implement the callback function in Java, and I to set up everything from the Java side, while the callback is executed from the C++ side.

Here's how my Java calling code could look like:

Caller caller = new Caller();
Callback callback = new JavaCallback();
 
caller.setCallback(callback);

caller.call(); // calls C++ which does the callback in Java


where JavaCallback is a Java class with my implementation of the callback:


class JavaCallback extends Callback {
    @Override
    public void run() {
        System.out.println("this is my java-side callback");
    }
}


And the C++ side that executes the callback would look like this:
// C++
class Callback { public: virtual void run() { ... } }; class Caller { private: Callback *_callback; public: Caller(): _callback(0) {} void setCallback(Callback *cb) { _callback = cb; } void call() { _callback->run(); } };


The above code is taken from this SWIG callback example.

Your help is very much appreciated!

Best regards,
Vito



Samuel Audet

unread,
Jul 25, 2018, 4:13:07 AM7/25/18
to javacpp...@googlegroups.com, vbag...@gmail.com
The example in the README.md file isn't just for when calling explicitly from C++, it works the same when passing pointers to a native library.

In your case, with new Info("Callback").virtualize() the Parser outputs something like the following:
public static class Callback extends Pointer {
    public Callback() { allocate(); }
    private native void allocate();
    @Virtual public native void run();
}

public static class Caller extends Pointer {
    public Caller() { allocate(); }
    private native void allocate();
    public native void setCallback(Callback cb);
    public native void call();
}
And we can use those peer classes pretty much in the way you describe.

Samuel

vbag...@gmail.com

unread,
Jul 27, 2018, 3:03:29 AM7/27/18
to javacpp
Dear Samuel,
many thanks for your reply - I'll try that out over the weekend!
Best regards,
Vito
Reply all
Reply to author
Forward
0 new messages