如何使用 ctypes 打包和解包(Structure <-> str)

2023-12-01

这可能是一个愚蠢的问题,但我在文档或任何地方都找不到好的答案。

如果我使用struct为了定义二进制结构,该结构有两种对称的序列化和反序列化方法(打包和解包),但似乎ctypes没有一个简单的方法来做到这一点。这是我的解决方案,感觉不对:

from ctypes import *

class Example(Structure):
    _fields_ = [
        ("index", c_int),
        ("counter", c_int),
        ]

def Pack(ctype_instance):
    buf = string_at(byref(ctype_instance), sizeof(ctype_instance))
    return buf

def Unpack(ctype, buf):
    cstring = create_string_buffer(buf)
    ctype_instance = cast(pointer(cstring), POINTER(ctype)).contents
    return ctype_instance

if __name__ == "__main__":
    e = Example(12, 13)
    buf = Pack(e)
    e2 = Unpack(Example, buf)
    assert(e.index == e2.index)
    assert(e.counter == e2.counter)
    # note: for some reason e == e2 is False...

PythonInfo 维基有一个解决方案。

常见问题解答:如何将字节从 ctypes.Structure 复制到 Python?

def send(self):
    return buffer(self)[:]

常见问题解答:如何从 Python 将字节复制到 ctypes.Structure?

def receiveSome(self, bytes):
    fit = min(len(bytes), ctypes.sizeof(self))
    ctypes.memmove(ctypes.addressof(self), bytes, fit)

Their send是(或多或少)等价于pack, and receiveSome有点像pack_into。如果您遇到“安全”的情况,即您要解包到与原始类型相同的结构中,则可以像这样将其单行memmove(addressof(y), buffer(x)[:], sizeof(y))复制x into y。当然,您可能会使用一个变量作为第二个参数,而不是文字包装x.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ctypes 打包和解包(Structure <-> str) 的相关文章

随机推荐