3

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++?

2
  • 3
    I'm not sure JNI works that way. You're calling a native method with jobject as parameter. On that object you can call a method as usual, knowing its name and signature. Commented Nov 20, 2012 at 15:35
  • It's also possible to create easily callbacks with JavaCPP. Let me know if you want need more details! Commented Dec 1, 2012 at 5:13

2 Answers 2

5

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:

// SWIGed C++
class IStringToBool
{
public:
    virtual bool call(std::string s) = 0;
}

class IStringToBoolUser
{
public:
    void setFunction(IStringToBool &function);
}

And then:

// Java
public class MyFunction implements IStringToBool {
    public bool call(String s) {
        // do something
        return true;
    }
}

Documentation: Cross language polymorphism using directors

Sign up to request clarification or add additional context in comments.

Comments

1

With JNI you could pass a object to C++, then you could take function pointer from the C++ Object.

1 Comment

The problem with this is that JNI function pointer (e.g. CallMethodVoid etc.) almost certainly doesn't match the function pointer you're looking for in C++. You need to pass in at least JNIEnv, the jobject and jmethodID.

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.