Search code examples
javaandroidjava-native-interfacenative

Passing function pointer from native to java


Im using JNI to call some functions from a java library (JAR). One of these functions requires a listener which has some callbacks (success and error). The functions needed to handle these callbacks are in native code. Is is possible to create a listener with these native functions from native code and pass it via JNI?

The interface itself is not public but it works the same as the InApp Purchase stuff where you use the google helper to launch the purchase flow with:

mHelper.launchPurchaseFlow(activity, mItems[idx], idx, mPurchaseFinishedListener, "");

The mPurcahseFinishedListener would then be something like

`

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener()
{
    public void onIabPurchaseFinished(IabResult result, Purchase purchase)
    {
        Log.v("YER", "Its here");
    }
};

`

The idea is the onIabPurchaseFinished function is actually a native code function.


Solution

  • To start with, you cannot pass a native-code function pointer to Java in such a way that the Java side can call the function, directly.

    But what you could do is map the function pointers to integer (or enum) tokens and return those to the Java world. Then you define and implement a native method for performing callbacks that takes a function pointer token as an argument. The method would reverse map the token to a function pointer, and then call the corresponding function to perform the callback action.