I use “protobuf-net” for Serializing a structure, but it returns an empty array.
public static byte[] PacketToArray(Packet packet)
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
Serializer.Serialize(stream, packet);
byte[] packetArray = stream.GetBuffer();
stream.Close();
return packetArray;
}
packetArray[] ist at the ending “{byte[0]}” but there should be some data in.
The data of “packet” is:
[ProtoContract]
public struct Packet
{
[ProtoMember(1)]
public int opcode;
[ProtoMember(2)]
public string message;
}
And in the testings the values vor opcode is 0 and for message its null.
Where is the Problem?
What makes you think there is a problem? 0 bytes is perfectly legal for protobuf-net, and is expected in this case as there is nothing interesting to serialize; it can deserialize a
0and anullwithout needing any external data. The key point here: if you deserialize that same zero bytes, you will get back aPacketwith a0opcode and anullmessage. Job done.If you want it to handle “framing” so that multiple messages can be read separately, then use
SerializeWithLengthPrefix(andDeserializeWithLengthPrefix), but: no problem here.Actually, there is a bug in your code, though:
If you use
GetBuffer()without also tracking the.Length, you will get the oversized backing buffer, which contains garbage (in this case zeros). UseToArray()instead. So: