[英]Convert Python ctypes.Structure into str
我有一个Structure
(在这种情况下是一个Netlink消息头)我需要通过套接字发送到内核。 我弄清楚的唯一方法是使用__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])
看起来__reduce__
用于序列化(pickle)并且依赖于它总是以相同的方式运行似乎是一个错误。
肯定有更好的办法?
我同意使用__reduce__()
感觉不对。
ctypes.string_at(ctypes.addressof(hdr), ctypes.sizeof(hdr))
应该以更透明的方式做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.