将Python ctypes.Structure转换为str

4 投票
1 回答
1555 浏览
提问于 2025-04-17 12:46

我有一个结构体(在这个例子中是一个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__是用来进行序列化(也就是把数据转换成可以存储或传输的格式),但总是依赖它以相同的方式工作似乎不太靠谱。

难道没有更好的方法吗?

1 个回答

6

我同意使用 __reduce__() 这个方法感觉不太对劲。

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

这样做会更简单明了。

撰写回答