Posted on 2019-11-20 00:00
魔のkyo 阅读(258)
评论(0) 编辑 收藏 引用 所属分类:
C++ 、
Python
import msgpack
def obj_dict_serializer(obj):
return msgpack.dumps(vars(obj))
def obj_dict_deserializer(T):
def deserializer(buf):
obj = T()
dic = msgpack.unpackb(buf)
for k,v in dic.items():
k = k.decode()
if type(v)==bytes:
v = v.decode()
setattr(obj, k, v)
return obj
return deserializer
def obj_list_serializer(obj):
return msgpack.dumps(list(vars(obj).values()))
def obj_list_deserializer(T):
def deserializer(buf):
obj = T()
for k, v in zip(vars(obj).keys(), msgpack.unpackb(buf)):
if type(v)==bytes:
v = v.decode()
setattr(obj, k, v)
return obj
return deserializer
if __name__ == '__main__':
from dataclasses import dataclass
@dataclass
class Stu:
id : int = 0
name: str = ""
stuno: str = ""
stu1 = Stu(1, "张三", "190003160")
stu2 = Stu(2, "李四", "190003161")
buf1 = obj_dict_serializer(stu1)
stu1_ = obj_dict_deserializer(Stu)(buf1)
print(stu1, stu1_)
print(stu1 == stu1_)
buf2 = obj_dict_serializer(stu2)
stu2_ = obj_dict_deserializer(Stu)(buf2)
print(stu2, stu2_)
print(stu2 == stu2_)
配合在C++上使用msgpack.hpp 像class、struct中添加 MSGPACK_DEFINE 或 MSGPACK_DEFINE_MAP,可以实现python和C++之间的数据互传后的编解码