如何解码原始原型字节数组

How to decode raw proto byte array

使用 HttpClient 我可以在协议缓冲区中获取字节数组数据。如何使用 protobuf-net without knowing the type? This Whosebug answer 解码它在我无法实例化 ProtoReader.

的最新版本中不再起作用

您仍然可以实例化 v3 中的 reader API。唯一的区别是您应该使用 Create 而不是 new,并且如果可能的话:使用新的 ProtoReader.State API。除此之外,应该基本保持不变。另外,您不再需要 MemoryStream(您可以直接使用 byte[] 等原始缓冲区)。

这是使用 v3 和 State API:

的翻译版本
static void Main()
{
    byte[] arr = // ...
    var reader = ProtoReader.State.Create(arr, null, null);
    try
    {
        WriteTree(ref reader);
    }
    finally
    {   // the rules on when you can "using" a ref-type
        // are ... complicated
        reader.Dispose();
    }
}
static void WriteTree(ref ProtoReader.State reader)
{
    while (reader.ReadFieldHeader() > 0)
    {
        Console.WriteLine(reader.FieldNumber);
        Console.WriteLine(reader.WireType);
        switch (reader.WireType)
        {
            case WireType.Varint:
                // warning: this appear to be wrong if the 
                // value was written signed ("zigzag") - to
                // read zigzag, add: pr.Hint(WireType.SignedVariant);
                Console.WriteLine(reader.ReadInt64());
                break;
            case WireType.String:
                // note: "string" here just means "some bytes"; could
                // be UTF-8, could be a BLOB, could be a "packed array",
                // or could be sub-object(s); showing UTF-8 for simplicity
                Console.WriteLine(reader.ReadString());
                break;
            case WireType.Fixed32:
                // could be an integer, but probably floating point
                Console.WriteLine(reader.ReadSingle());
                break;
            case WireType.Fixed64:
                // could be an integer, but probably floating point
                Console.WriteLine(reader.ReadDouble());
                break;
            case WireType.StartGroup:
                // one of 2 sub-object formats
                var tok = reader.StartSubItem();
                WriteTree(ref reader);
                reader.EndSubItem(tok);
                break;
            default:
                reader.SkipField();
                break;
        }
    }
}

(非State API仍然可用,但这是首选)