如何使用 ctypes (Structure <-> str) 打包和解包 [英] How to pack and unpack using ctypes (Structure <-> str)

查看:35
本文介绍了如何使用 ctypes (Structure <-> str) 打包和解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This might be a silly question but I couldn't find a good answer in the docs or anywhere.

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

If I use struct to define a binary structure, the struct has 2 symmetrical methods for serialization and deserialization (pack and unpack) but it seems ctypes doesn't have a straightforward way to do this. Here's my solution, which feels wrong:

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 wiki 有对此的解决方案.

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

FAQ: How do I copy bytes to Python from a ctypes.Structure?

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

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

FAQ: How do I copy bytes to a ctypes.Structure from Python?

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

他们的 send 是(或多或少)pack 的等价物,而 receiveSome 是一种 pack_into.如果你有一个保险箱"在您解压到与原始结构相同类型的结构中的情况下,您可以像 memmove(addressof(y), buffer(x)[:], sizeof(y))x 复制到 y 中.当然,您可能会有一个变量作为第二个参数,而不是 x 的文字包装.

Their send is the (more-or-less) equivalent of pack, and receiveSome is sort of a pack_into. If you have a "safe" situation where you're unpacking into a struct of the same type as the original, you can one-line it like memmove(addressof(y), buffer(x)[:], sizeof(y)) to copy x into y. Of course, you'll probably have a variable as the second argument, rather than a literal packing of x.

这篇关于如何使用 ctypes (Structure <-> str) 打包和解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆