SWIG C函数指针和JAVA [英] SWIG C function pointer and JAVA
问题描述
我有一些code C和方法的一个有一个函数指针作为参数。我试图用C code在我的Android应用程序。
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.
我决定用SWIG做所有的工作,产生我需要的java文件。一切都与常规功能(一说没有一个函数指针作为参数)效果很好。
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).
但我不知道我怎么能够通过我的Java方法回调到C函数。
But I'm not sure how I can pass my JAVA method as a callback to the C function.
下面是一个例子:
这是我的multiply.h文件
here is my multiply.h file
typedef int (*callback_t) (int a, int b, int c);
int foo(callback_t callback);
这是我的multiply.c文件
here is my multiply.c file
#include <stdio.h>
#include "multiply.h"
int foo(callback_t callback)
{
return callback(2, 4, 6);
}
这是我的接口文件乘swig.i
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"
然后我跑到下面痛饮命令生成我需要的java文件
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
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
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
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;
}
}
现在我怎么能称之为富
方法从我的Java code?该参数的类型是 SWIGTYPE_p_f_int_int_int__int
的?我不明白我怎么能传递一个Java方法回调到C code ......我想我肯定失去了一些东西......
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 ....
任何帮助是AP preciated,谢谢
Any help is appreciated, thanks
推荐答案
显然,你无法通过一个单一的方法作为参数。但是回调仍然是可能通过一个接口实现回调导演功能。请参见这个例子。
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.
这篇关于SWIG C函数指针和JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!