python 的 ctypes 和 swig 之间的互操作性

Interoperability between ctypes and swig for python

我有一个用 swig 包装的 C 文件。这个 C 文件包含一个 API 函数指针作为参数(如下所示)。

example.c

int binary_op (int a, int b, int (*op)(int,int))
{
    return (*op)(a,b);
}

我可以将函数映射到指针参数,前提是映射函数是使用 swig 在同一文件中定义的。但是映射函数是在另一个用 Ctypes 包装的 C 文件中定义的。

testing.c

int add_int(int a, int b){
     return a+b;
}

在Python中,我导入了swig生成的模块,并用ctypes生成的映射函数调用了API,结果出错。

在testfile.py

import example # Module generated by swig

from ctypes import *
wrap_dll = CDLL('testing.dll') # testing.dll is generated with File_2.c

# Mapping function 'add_int' to argument in 'binary_op'
example.binary_op(3,4,wrap_dll.add_int)

显示的错误是参数类型不匹配。

TypeError: in method 'binary_op', argument 3  of type 'int (*)(int,int)'

我在 python 中创建了如下所示的 ctypes 函数:

py_callback_type = CFUNCTYPE(c_void_p, c_int, c_int)

其中 return 类型和参数类型类似于函数指针参数。现在我将映射函数 'add' 包装到上面的 ctypes 函数中。

f = py_callback_type(add)

最后我将包装函数转换为 return 类型作为指针,'.value' 给出了包装指针函数的地址。

f_ptr = cast(f, c_void_p).value

然后在 swig 接口文件中,使用类型映射,我将指针参数更改如下:

extern int binary_op (int a, int b, int INPUT);

现在,当我将函数映射到指针时,映射函数的地址将作为整数 INPUT 传递给 binary_op 函数。 由于参数是指针,所以地址中的函数会被映射。

example.binary_op(4,5,f_ptr) ==> 9 //mapped function is 'add(int a, int b)' --> returns a+b