2
votes

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?

1
I suggest you call ToByteArray() instead of GetBuffer() - it won't fix this problem, but it will give you a byte array with the right amount of data, when you've got the rest working. - Jon Skeet

1 Answers

3
votes

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 0 and a null without needing any external data. The key point here: if you deserialize that same zero bytes, you will get back a Packet with a 0 opcode and a null message. Job done.

If you want it to handle "framing" so that multiple messages can be read separately, then use SerializeWithLengthPrefix (and DeserializeWithLengthPrefix), but: no problem here.

Actually, there is a bug in your code, though:

byte[] packetArray = stream.GetBuffer();

If you use GetBuffer() without also tracking the .Length, you will get the oversized backing buffer, which contains garbage (in this case zeros). Use ToArray() instead. So:

public static byte[] PacketToArray(Packet packet) {
    using(MemoryStream stream = new MemoryStream()) {
        Serializer.Serialize(stream, packet); // or SerializeWithLengthPrefix
        return stream.ToArray();
    }
}