在python中将对象转换为字节数组,反之亦然

问题描述 投票:0回答:1

[我使用Python并向/从外部c ++服务器发送和接收数据包(因此,pickle无法帮助),并且需要将python对象序列化和反序列化到/来自字节数组。

序列化很容易:

class MsgBase(Structure):
    def __init__(self, my_type):
        self.m_type = my_type

    def get_buffer(self):
        return bytearray(self)

    _pack_ = 1
    _fields_ = [
        ('m_type', c_uint8)]

message = MsgBase(1)
arr = message.get_buffer()

但是如何反序列化此缓冲区?

需要这样的东西:

message = MsgBase(0)
message.deserialize_from_bytearray(arr)
python networking serialization message
1个回答
0
投票

我找到了解决方法:

消息= MsgBase.from_buffer(arr)

© www.soinside.com 2019 - 2024. All rights reserved.