2012-02-10 113 views
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__是序列化(鹹菜),並根據它的功能總是以同樣的方式似乎是一個錯誤。

必須有更好的方法嗎?

+1

更好地解釋和回答:http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str – tMC 2012-02-10 19:25:31

回答

5

我同意使用__reduce__()感覺不對。

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

應該以更透明的方式來解決問題。

+1

行政長官,這真棒。我愛'ctypes' – tMC 2012-02-10 15:48:49