4

I have a Structure (in this case is a Netlink Msg Header) that I need to send across the socket to the kernel. The only way I've figured out is to use __reduce__().

>>> class nlmsghdr(ctypes.Structure):
...     _fields_ = [('nlmsg_len', ctypes.c_int32),
...                 ('nlmsg_type', ctypes.c_int16),
...                 ('nlmsg_flags', ctypes.c_int16),
...                 ('nlmsg_seq', ctypes.c_int32),
...                 ('nlmsg_pid', ctypes.c_int32)]
... 
>>> 
>>> hdr = nlmsghdr(20, 22, 769, 1328884876, 0)
>>> hdr.__reduce__()[1][1][1]
'\x14\x00\x00\x00\x16\x00\x01\x03\x8c,5O\x00\x00\x00\x00'
>>> # socket.send(hdr.__reduce__()[1][1][1])

It looks like __reduce__ is for serializing (pickle) and depending on it to always function the same way seems like a mistake.

There must be a better way?

tMC
  • 18,105
  • 14
  • 62
  • 98
  • 1
    Better explained and answered: http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str – tMC Feb 10 '12 at 19:25

1 Answers1

6

I agree that using __reduce__() feels wrong.

ctypes.string_at(ctypes.addressof(hdr), ctypes.sizeof(hdr))

should do the trick in a more transparent way.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841