gpt4 book ai didi

python - 将 Python ctypes.Structure 转换为 str

转载 作者:太空狗 更新时间:2023-10-30 02:34:15 25 4
gpt4 key购买 nike

我有一个 Structure(在本例中是一个 Netlink Msg Header),我需要通过套接字将其发送到内核。我想出的唯一方法是使用 __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))

应该以更透明的方式实现这一目的。

关于python - 将 Python ctypes.Structure 转换为 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9229853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com