Error in size of byte array during deserialization

I am using the protobuf-net serializer and so far, it has worked perfectly. I have a case where some private integer members must be serialized, but they must be assembled into a byte array before serialization, and then extracted from the byte array during deserialization, but the size of the byte array changes during deserialization.

In the following code, I simplified and illustrated this problem by having a class containing an integer, and when serialized, it is accessible through a getter, which converts it to an array of bytes of length 4. When dererilization, the process is canceled, but the setter is assigned an array of bytes twice the size ( 8), and this causes errors. Is it impossible to do for such a conversion?

Note that the last four entries in a byte array of size 8 actually contain values ​​that are serialized. Why?

The array returned PrivateValue: [54, 100, 0, 0]but the array specified when deserializing: [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);
        }
    }
}
+3
source share
2 answers

After further research, I found this protobuf-net OverwriteList post on a byte array on SO, which explains that this is a bug in protobuf and needs to be resolved in a future version.

+2
source

I guess it serializes the field Value. Try marking it to ignore and see if this helps:

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

All Articles