“Invalid field in source data: 0” error with ProtoBuf-Net and Compact Framework

后端 未结 2 1230
旧时难觅i
旧时难觅i 2021-02-20 08:24

Is anyone aware of any issues when using ProtoBuf-Net to serialize/deserialize between compact framework and the full .Net framework? I have a class called LogData that I am se

相关标签:
2条回答
  • 2021-02-20 09:07

    Easy one: you use:

    var buffer = ms.GetBuffer();
    

    And then buffer.Length. That means you are using the oversized, padded buffer. If you do that you need to use ms.Length, which will tell you the actual length. Alternatively, ms.ToArray() may be used, but that involves an extra copy.

    My advice: keep using GetBuffer(), but only write ms.Length bytes, not buffer.Length bytes.

    Once you have removed these extra incorrect zeros, I expect you'll find it works.

    0 讨论(0)
  • 2021-02-20 09:09

    I realize the main developer @MarcGravell already answered but I just wanted to share my own $0.02 that helped me on this issue. If I have a fixed size byte[] and get a count of bytes read in return, I can just specify that in the MemoryStream declaration and it solves the issue. Also, as it applies to the OP, don't declare the MemoryStream until you're done reading.

    byte[] msg = new byte[4096];
    int bytesRead = someStreamClass.Read(msg, 0, 4096);
    using (MemoryStream ms = new MemoryStream(msg, 0, bytesRead))
    {    
        logData = Serializer.Deserialize<LogData>(ms);
    }
    

    @MarcGravell: Thanks for this great library!

    0 讨论(0)
提交回复
热议问题