gpt4 book ai didi

java - SWIG C 函数指针和 JAVA

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:40 26 4
gpt4 key购买 nike

我有一些 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);
}

这是我的接口(interface)文件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;
}
}

现在如何从我的 java 代码中调用此 foo 方法?参数的类型为 SWIGTYPE_p_f_int_int_int__int ???我不明白如何将 JAVA 方法作为回调传递给 C 代码……我想我肯定在这里遗漏了一些东西……

感谢任何帮助,谢谢

最佳答案

显然,您不能将单个方法作为参数传递。但是通过在接口(interface)中实现回调,“Director”功能仍然可以进行回调。参见 this example .

关于java - SWIG C 函数指针和 JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com