我有一些 C 代码,其中一个方法有一个函数指针作为参数。我正在尝试在我的 Android 应用程序中使用 C 代码。
我决定使用 SWIG 来完成生成我需要的 java 文件的所有工作。一切都适用于常规函数(没有函数指针作为参数的函数)。
但我不确定如何将 JAVA 方法作为回调传递给 C 函数。
这是一个例子:
这是我的 multiply.h 文件
typedef int (*callback_t) (int a, int b, int c);
int foo(callback_t callback);
这是我的multiply.c 文件
#include <stdio.h>
#include "multiply.h"
int foo(callback_t callback)
{
return callback(2, 4, 6);
}
这是我的接口文件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"
然后我运行以下 swig 命令来生成我需要的 java 文件
swig -java -package com.example.ndktest -o multiply-wrap.c mulitiply-swig.i
然后 swig 生成了以下文件:
示例.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));
}
}
示例JNI.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;
}
}
现在我该怎么称呼这个foo
我的java代码中的方法?参数的类型SWIGTYPE_p_f_int_int_int__int
???我不明白如何将 JAVA 方法作为回调传递给 C 代码......我想我肯定在这里遗漏了一些东西......
任何帮助表示赞赏,谢谢