5

I have some code in C and one of the method has a function pointer as argument. I'm trying to use the C code in my Android app.

I decided to use SWIG to do all the work in generating the java files I need. Everything works well with regular function (the one that doesn't have a function pointer as argument).

But I'm not sure how I can pass my JAVA method as a callback to the C function.

Here is an example :

here is my multiply.h file

typedef int (*callback_t) (int a, int b, int c);

int foo(callback_t callback);

here is my multiply.c file

#include <stdio.h>
#include "multiply.h"

int foo(callback_t callback)
{
    return callback(2, 4, 6);
}

here is my interface file multiply-swig.i

%module example
 %{
 /* Includes the header in the wrapper code */
 #include "multiply.h"
 %}

 /* Parse the header file to generate wrappers */
 %include "multiply.h"

then I ran the following swig command to generate the java files I need

swig -java -package com.example.ndktest -o multiply-wrap.c mulitiply-swig.i 

and then swig generated the following files :

example.java

package com.example.ndktest;

public class example {
  public static int foo(SWIGTYPE_p_f_int_int_int__int callback) {
    return exampleJNI.foo(SWIGTYPE_p_f_int_int_int__int.getCPtr(callback));
  }

}

exampleJNI.java

package com.example.ndktest;

public class exampleJNI {
  public final static native int foo(long jarg1);
}

SWIGTYPE_p_f_int_int_int__int.java

package com.example.ndktest;

public class SWIGTYPE_p_f_int_int_int__int {
  private long swigCPtr;

  protected SWIGTYPE_p_f_int_int_int__int(long cPtr, boolean futureUse) {
    swigCPtr = cPtr;
  }

  protected SWIGTYPE_p_f_int_int_int__int() {
    swigCPtr = 0;
  }

  protected static long getCPtr(SWIGTYPE_p_f_int_int_int__int obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
}

Now how can I call this foo method from my java code? The argument is of type SWIGTYPE_p_f_int_int_int__int ??? I don't understand how I can pass a JAVA method as callback to the C code ... I think I am definitely missing something here ....

Any help is appreciated, thanks

pdiddy
  • 6,217
  • 10
  • 50
  • 111
  • 2
    I wrote a worked example of a similar use case in Java at: http://stackoverflow.com/a/12251183/168175 – Flexo Dec 13 '13 at 07:29

1 Answers1

0

Obviously, you cannot pass a single method as an argument. But callbacks are still possible with "Director" feature via implementing callback in an interface. See this example.

Alexander Solovets
  • 2,447
  • 15
  • 22