Reputation: 19315
This doesn't work:
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))
]
It errors with:
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
However I can set the values in __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
Is this the 'correct' way to do this, via __init__
?
Upvotes: 5
Views: 2486
Reputation: 1756
Your example errors because ctypes.c_uint(0xFFFFFFFF)
is not a type. In the class definitions everything has to be a type (pointers would be POINTER
not pointer
).
I think that the __init__
method you use if just fine. I have wrapped some really large structures and typically use __init__
just like you have done to set default values.
In general if you have control of the C library that you are wrapping I think that you should not have default setting in both places (C and Python). In one large library I wrapped where I have access to the C I created C functions "set_defaults" that I call from the __init__
. This way C only users have access to the defaults and there is only one set of code to maintain.
Upvotes: 2