如何打包和解包使用ctypes的(结构< - > STR)
题
这可能是一个愚蠢的问题,但在文档中我找不到一个很好的答案或任何地方。
如果我使用结构以定义一个二进制结构,该结构具有用于序列化和反序列化(pack和unpack)2种对称的方式,但它似乎的 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维基具有用于此的解决方案。
常见问题:我如何复制字节到Python从ctypes.Structure
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)
他们send
是pack
的(更多或更少)等效,和receiveSome
是排序一个pack_into
的。如果你有一个“安全”的情况下,你要拆包到同一类型与原始的结构,可以一行像memmove(addressof(y), buffer(x)[:], sizeof(y))
到x
复制到y
。当然,你可能有一个变量作为第二个参数,而不是x
的文字包装。
其他提示
有一个在二进制此链接的I / O在python:
http://www.dabeaz.com /blog/2009/08/python-binary-io-handling.html
根据此可以简单的写下面从缓冲区读取(不只是文件):
g = open("foo","rb")
q = Example()
g.readinto(q)
要写入仅仅是:
g.write(q)
同样对于使用套接字:
s.send(q)
和
s.recv_info(q)
我做了一些测试用包/解包和ctypes的和该方法是除了在C
直写最快测试在Python3
e = Example(12, 13)
serialized = bytes(e)
deserialized = Example.from_buffer_copy(serialized)
不隶属于 StackOverflow