【发布时间】:2010-12-21 23:52:34
【问题描述】:
这可能是一个愚蠢的问题,但我在文档或任何地方都找不到好的答案。
如果我使用 struct 定义二进制结构,则该结构有 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...
【问题讨论】:
-
这看起来对我来说是正确的。 ctypes 不是用于序列化的,所以你可以用 7 行代码来完成这一事实实际上看起来很不错。