Setting default ctypes.Structure values

This does not 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)) ] 

These are 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 right way to do this via __init__ ?

+4
source share
1 answer

An example of your mistakes is because ctypes.c_uint(0xFFFFFFFF) not a type. In class definitions, everything must be a type (pointers will be POINTER not POINTER ).

I think the __init__ method you use if just fine. I wrapped some really big structures and usually used __init__ just like you did to set the default values.

In the general case, if you have control over the C library that you are wrapping, I think you should not set the default in both places (C and Python). In one large library, I wrapped up where I have access to C. I created C functions "set_defaults" that I call from __init__ . Thus, in C, only users have access to default values, and only one set of code is supported.

+2
source

Source: https://habr.com/ru/post/1397104/


All Articles