使用Swift以二进制格式解码Protobuf

时间:2019-10-28 08:42:03

标签: python swift protocol-buffers google-protocol-buffer swiftprotobuf

我是Protobuf的新手,我想快速解码Protobuf(语法2类型)。下面我分享了我正在迅速使用的库

'SwiftProtobuf'

我有一个原型文件,在编译器的帮助下,我生成了一个proto.pb.swift文件并将其添加到项目中

第1步:我正在我的应用中接收protobuf数据,但是无法解码此消息。

我使用了以下代码:

// Deserialize a received Data object from `binaryData`
let decodedInfo = try User(serializedData: bytesReceived)

以下是我关注的链接 https://medium.com/@dzungnguyen.hcm/protobuf-in-swift-809658ecdb22

向前移动,我传递了partial == true,那么我可以获取User数据,但其所有值都是垃圾,例如:time = -1532154564212诸如此类

所以我想检查一下我在以下代码行中使用过的字节数据

let array = bytesReceived.withUnsafeBytes {
                [UInt8](UnsafeBufferPointer(start: $0, count: bytesReceived.count))
            }

下面是数组的值

[122、43、10、10、8、128、192、4、16、128、128、160、140、6、21、165、165、165、165、24、143、255、255, 255,15,32,172,255,255,255,15,40,129,8,.... 160,140]

我的一个python开发人员朋友已经在我共享他的Python代码的下面屏蔽了protobuf消息

data = bytearray(proto_data)
 length, pos = 0, 0

    # 
    while pos < len(data):
        msg = Myproto.User()              
        # find the position and length of submessage
        length, pos = _DecodeVarint32(data, pos)

        try:
            msg.ParseFromString(data[pos:(pos + length)])
        except:
            pass

        pos += length
        print("Msg: ", msg)

msg.ParseFromString(data [pos:(pos +长度)])

我没有得到python中ParseFromString方法的确切作用

请帮助我,我们如何在Swift中解码此protobuf消息。 在此先感谢

0 个答案:

没有答案