I want to call a native c++ method from java (android) code, and pass a java function as a parameter, so I will be able to save the function pointer in the c++ code, and activate it from the native code.
I chose to implement the function pointer in java using anonymous class, and I call the native function from java as following:
interface FunctionPtrHelper {
bool function(String param);
}
NativeFunc(param1,param2,new FunctionPtrHelper() {
public bool myFunction(String param) {
//body of my function
}});
How can I make swig/jni know the 3rd param (which is actually a class) and translate it to a function pointer in c++ (that will contain’myFunction’) ?
In case it is not possible, is there another way to pass a function pointer from java to c++?
You can write a C++ interface and SWIG it as a “director” class. Then you can implement the interface in Java. Instantiate the implementation object in Java and pass it into a C++ method that takes a pointer or reference to the interface, and C++ will be able to call back into your Java class. For example:
And then:
Documentation: Cross language polymorphism using directors