Python ctypes 结构:可以在不定义 class / 内联的情况下制作吗?

Python ctypes structure: possible to be made without defining a class / inline?

是否可以将 ctypes 结构的实例传递给库,而无需先将其定义为 class?我有这样的情况,我只需要实例化每个结构一次,并将指向它的指针传递给动态加载的库,所以感觉有点...... odd/unnecessary 有制作 class.

似乎没有内置任何东西,但你可以定义一个函数,这样大部分代码就不必直接class

def make_struct(fields):
    class Struct(Structure):
        _fields_ = [(field_name, field_type) for (field_name, field_type, _) in fields]
    return Struct(*tuple(value for (_, _, value) in fields))

使用示例

my_struct = make_struct((
    ('my_first_field', c_int, 1),
    ('my_second_field', c_double, 1.0),
))

(这是在 https://github.com/michalc/sqlite-s3-query/blob/main/sqlite_s3_query.py 完成的)