这可能是一个愚蠢的问题,但我无法在文档或任何地方找到一个好的答案.
如果我使用struct来定义二进制结构,那么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...
Run Code Online (Sandbox Code Playgroud)