SWIG C函数指针和JAVA

 lovely叫我龙哥 发布于 2023-02-11 11:06

我在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 
#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;
  }
}

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

任何帮助表示赞赏,谢谢

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有