python ctypes structure_python – 设置ctypes.Structure默认值

这不起作用:class ifinfomsg(ctypes.Structure):_fields_[(ifi_family,ctypes.c_ubyte),(__ifi_pad, ctypes.c_ubyte

这不起作用:

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

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而不是指针).

我认为你使用的__init__方法就好了.我已经包装了一些非常大的结构,并且通常使用__init__,就像你设置默认值一样.

一般来说,如果你控制了你正在包装的C库,我认为你不应该在两个地方(C和Python)都有默认设置.在我访问C的一个大型库中,我创建了C函数“set_defaults”,我从__init__调用它.这样C只有用户才能访问默认值,并且只有一组代码需要维护.

发布者:admin,转转请注明出处:http://www.yc00.com/web/1755047564a5232934.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信