SWIG C function pointer and JAVA

久未见 提交于 2019-12-10 14:40:05

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/20551476/swig-c-function-pointer-and-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!