aweis
aweis

Reputation: 5606

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);
        }
    }
}

Upvotes: 3

Views: 1518

Answers (2)

aweis
aweis

Reputation: 5606

After further research i found this post protobuf-net OverwriteList on Byte Array on SO, that explained that it is a bug in the protobuf, and it should be solved in a future version.

Upvotes: 2

SwDevMan81
SwDevMan81

Reputation: 50008

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; }

Upvotes: 0

Related Questions