【发布时间】:2021-08-06 18:06:18
【问题描述】:
在 python-cffi 框架中使用 API mode, calling C sources instead of a compiled library 我想在 python 中使用关键字参数调用我的 c 函数。 cffi 中是否有为此的内置功能?否则我将不得不围绕我的 cffi 包装的 c 函数编写一个 python 包装器,我不想这样做,因为它看起来像一个丑陋的解决方案。
(使用 python 运行这两个文件,如果 cffi 和 gcc 存在,应该可以开箱即用:“python example_extension_build.py && python test_example.py”)
注意:在此示例代码中,我使用 API level, out-of-line 模式代替(用于 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("%s\n", 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
【问题讨论】:
标签: python c wrapper keyword-argument python-cffi