繁体   English   中英

设置ctypes结构默认值

[英]Setting ctypes.Structure default values

这不起作用:

class ifinfomsg(ctypes.Structure):
    _fields_ = [
                 ('ifi_family',  ctypes.c_ubyte),
                 ('__ifi_pad',   ctypes.c_ubyte),
                 ('ifi_type',    ctypes.c_ushort),
                 ('ifi_index',   ctypes.c_int),
                 ('ifi_flags',   ctypes.c_uint),
                 ('ifi_change',  ctypes.c_uint(0xFFFFFFFF))
               ]

出现以下错误:

  File "rtnetlink.py", line 243, in <module>
    class ifinfomsg(ctypes.Structure):
TypeError: Error when calling the metaclass bases
    second item in _fields_ tuple (index 5) must be a C type

但是我可以在__init__()设置值:

class ifinfomsg(ctypes.Structure):
    _fields_ = [
                 ('ifi_family',  ctypes.c_ubyte),
                 ('__ifi_pad',   ctypes.c_ubyte),
                 ('ifi_type',    ctypes.c_ushort),
                 ('ifi_index',   ctypes.c_int),
                 ('ifi_flags',   ctypes.c_uint),
                 ('ifi_change',  ctypes.c_uint)
               ]

    def __init__(self):
        self.__ifi_pad = 0
        self.ifi_change = 0xFFFFFFFF

通过__init__这样做是“正确”的方法吗?

您的示例错误,因为ctypes.c_uint(0xFFFFFFFF)不是类型。 在类定义中,所有内容都必须是类型(指针将是POINTER而不是pointer )。

我认为您使用的__init__方法就可以了。 我包装了一些非常大的结构,并且通常使用__init__ ,就像您设置默认值一样。

通常,如果您控制着要包装的C库,我认为您不应该在两个地方(C和Python)都使用默认设置。 在一个大型库中,我包装了可以访问从__init__调用的CI创建的C函数“ set_defaults”的位置。 这样,只有C用户才可以访问默认值,并且只有一组代码可以维护。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM