简体   繁体   中英

Error in the size of byte array at deserialization

I am using the protobuf-net serializer and up til now, it has functioned perfect. I have a case where some private integer members must be serialized, but they must be gathered in a byte array before the serializing and then extracted from a byte array at deserialization, but the size of the byte array are changed at deserialization.

In the following code i have simplified and illustrated this problem by having a class containing an integer and when serializing, it is accessed through a getter that converts it into a byte array of length 4. At derserilization the process is reversed, but the setter is assigned a byte array twice the size (8) and this cause errors. is it not possible to do this kind of conversion?

Note that the last four entries in the byte array of size 8, actually contains the values that are serialized. Why?

The array that is returned by the PrivateValue is: [54, 100, 0, 0] but the array given when deserializing is: [0, 0, 0, 0, 54, 100, 0, 0] .

[ProtoBuf.ProtoContract]
class SerializeTest
{
    public int Value { get; set; }

    [ProtoBuf.ProtoMember(1)]
    private byte[] PrivateValue
    {
        get
        {
            return new byte[4]
            {
                (byte)(Value),
                (byte)(Value >> 8),
                (byte)(Value >> 16),
                (byte)(Value >> 24)
            };
        }
        set
        {
            // For some reasone is the given byte array is always twice the size
            // and all the values are in the last part og the array
            this.Value = ((int)value[3] << 24) | ((int)value[2] << 16) | ((int)value[1] << 8) | value[0];
        }
    }

    public override string ToString()
    {
        return this.Value.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var a = new SerializeTest() { Value = 25654 };

        using (var memStream = new MemoryStream())
        {
            // Serialize
            ProtoBuf.Serializer.Serialize(memStream, a);
            memStream.Position = 0;
            // Deserialize
            var data = ProtoBuf.Serializer.Deserialize<SerializeTest>(memStream);
            // Writs 0 and not 25654
            Console.WriteLine(data.Value);
        }
    }
}

经过进一步研究后,我在SO 发现了这个帖子protobuf-net OverwriteList on Byte Array ,这解释了它是protobuf中的一个bug,应该在未来的版本中解决。

My guess is that its serializing the Value field as well. Try marking it for ignore and see if that helps:

[ProtoIgnore]
public int Value { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM