如何用python-cffi包装C函数,使pythons的关键字参数起作用



使用API模式,调用C源代码,而不是python-cfi框架中的编译库我想用关键字参数在python中调用我的C函数。cffi中有内置功能吗?否则,我将不得不围绕我的cffi封装的c函数编写一个python包装器,我不想这样做,因为这似乎是一个丑陋的解决方案。

(使用python运行这两个文件,如果存在cffi和gcc,应该可以开箱即用:"python example_extension_build.py&python test_example.py">(

注意:在这个示例代码中,我使用API级别的离线模式(对于clearnes(

# file: example_extension_build.py
from cffi import FFI
ffibuilder = FFI()
# objects shared between c and python
ffibuilder.cdef("""
struct my_s{ int a; char * b; };
int my_f(int, struct my_s);
""")
# definitions of the python-c shared objects
ffibuilder.set_source("_example",r"""
struct my_s{ int a; char * b; };
#include <stdio.h>
int my_f(int arg_1, struct my_s arg_2) // some random example function
{
printf("%sn", arg_2.b); 
return arg_1 + arg_2.a;
}
""", sources=[])
if __name__ == "__main__" :
ffibuilder.compile(verbose=True)

python调用

# file: test_example.py
import _example as e
n = 21;
s = e.ffi.new("struct my_s *")
s.a = 21
s.b = e.ffi.new("char[]", b"Hello World!")
# e.lib.my_f(arg_2=s[0], arg_1=n); # <-- Here is what I want
e.lib.my_f(n, s[0]); # the standard way

截至今天——2021年5月18日——不可能用cffi包装c函数,以便向python公开关键字参数。这个答案是由Armin Rigo在这里的cffi邮件列表上提供的(如果满足某些条件,Armin Riggo将接受提供此功能的补丁(。唯一可能的解决方案是将cffi封装的c函数封装在python代码(ugh(中。

注意:如果想为arg_2 设置默认参数值,它会变得更难看

# file: test_wrap.py
import _example as e
def my_f(arg_1, arg_2) :
return e.lib.my_f(arg_1, arg_2)
n = 21
s = e.ffi.new("struct my_s *")
s.a = 21
s.b = e.ffi.new("char[]", b"Hello World!")
sol = my_f(arg_2=s[0], arg_1=n) # <-- Here is what I want
print(sol)

在命令行上

$ python test_wrap.py
Hello World!
42

最新更新