簡體   English   中英

如何用 python-cffi 包裝 C 函數以便 pythons 關鍵字參數起作用?

[英]How to wrap a C-function with python-cffi so that pythons keyword-arguments work?

使用API 模式,調用 C 源代碼而不是 python-cffi 框架中的已編譯庫我想在 Z23EEEB4347BDD26BFC6B7EE9A3B755DDBD89EDEFB7777777BDD26BFC6B7EE9A3B755BDD829EDFZ777777B755DDBDABD89 中調用我的 c 函數。 cffi 中是否有為此的內置功能? 否則,我將不得不圍繞我的 cffi 包裝的 c 函數編寫一個 python 包裝器,我不想這樣做,因為它看起來像一個丑陋的解決方案。

使用 python 運行這兩個文件,如果 cffi 和 gcc 存在,則應該開箱即用:“python example_extension_build.py && python test_example.py”

注意:在此示例代碼中,我使用API 級別,離線模式代替(用於清除)

# 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

As of today – May 18 2021 – it is not possible to wrap a c function with cffi as to expose keyword arguments to python. 此答案由 Armin Rigo 在此處的 cffi 郵件列表中提供(如果滿足某些條件, Armin Rigo將接受提供此功能的補丁)。 唯一可能的解決方案是將 cffi 包裝的 c 函數包裝在 python 代碼中(呃)。

注意:如果想為 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM