如何在python-cffi中实例化一个结构?

2024-05-19 20:11:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python cffi库实例化一个结构。我想从我自己的.h文件和标准库中实例化一个结构。在

import datetime
import os
from cffi import FFI

clib = None

script_path = os.path.dirname(os.path.realpath(__file__))

ffi = FFI()
with open(os.path.join(script_path, 'myheader.h'), 'r') as myfile:
    source = myfile.read()
    ffi.cdef(source)
clib = ffi.dlopen('mylib')

# these all fail
ffi.new("struct tm")
ffi.new("struct tm[]", 1)
ffi.new("struct tm *")
ffi.new("struct mystruct")

Tags: path实例importsourcenewosscriptclib
1条回答
网友
1楼 · 发布于 2024-05-19 20:11:54

ffi.new("struct mystruct")不正确,你可能是说ffi.new("struct mystruct *")。在

struct tm很可能在cdef()中没有定义,也就是说,在您的例子中,myheader.h中没有提到它。在使用它之前,您需要在cdef()中定义它,即使它在一个常见的标准报头中也是如此。在

您最好使用set_source()来实现这一点(API模式),因为您可以使用struct tm的近似定义,例如:

struct tm {
    int tm_sec;
    int tm_min;
    int tm_hour;
    int tm_mday;
    int tm_mon;
    int tm_year;
    ...;       /* literally a "..." here */
};

如果使用dlopen()(ABI模式),则必须使用与平台头中完全相同的声明。结果不太容易携带。在

相关问题 更多 >