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
{
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())
{
ProtoBuf.Serializer.Serialize(memStream, a);
memStream.Position = 0;
var data = ProtoBuf.Serializer.Deserialize<SerializeTest>(memStream);
Console.WriteLine(data.Value);
}
}
}
aweis source
share