C语言 ctypes 和 swig for python 之间的互操作性



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

例子.c

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

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

测试.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)

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

f = py_callback_type(add)

最后,我将返回类型包装的函数转换为指针,".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

最新更新