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

查看:157
本文介绍了如何使用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)[:]

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

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)


他们的发送是(或多或少)等价的 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天全站免登陆