4
我有一个Structure
(在这种情况下是一个Netlink消息头),我需要通过套接字发送到内核。我想出的唯一方法是使用__reduce__()
。将Python ctypes.Structure转换为str
>>> 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])
看起来__reduce__
是序列化(咸菜),并根据它的功能总是以同样的方式似乎是一个错误。
必须有更好的方法吗?
更好地解释和回答:http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str – tMC 2012-02-10 19:25:31