Search code examples
java-native-interface

JNI C++ Callbacks


I have a c++ function which accepts a lambda as a parameter. This function calls a piece of java code.

I was wondering how would I get the java code to call the lambda once it's done, in effect calling back to the C++ code.


Solution

  • JavaCPP does that. For example, the following code in C++:

    #include "jniFoo.h"
    
    int main() {
        JavaCPP_init(0, NULL);
        foo(6, 7);
    }
    

    With this Java class:

    import com.googlecode.javacpp.*;
    import com.googlecode.javacpp.annotation.*;
    
    public class Foo {
        public static class Callback extends FunctionPointer {   
            public @Name("foo") void call(int a, int b) { 
                System.out.println("bar " + a * b);
            }
        }
    }
    

    Produces the following output:

    bar 42