【问题标题】:SWIG C function pointer and JAVASWIG C 函数指针和 JAVA
【发布时间】:2013-12-31 08:02:15
【问题描述】:

我有一些 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 生成了以下文件:

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;
  }
}

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

感谢任何帮助,谢谢

【问题讨论】:

标签: java android function-pointers swig


【解决方案1】:

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

【讨论】:

  • 你有 C 的例子吗?不是cpp?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多