views:

266

answers:

1

I am looking for the protobuf-net equivalent to the C++ API Message::ByteSize to find out the serialized message length in bytes.

+1  A: 

I haven't played with the C++ API, so you'll have to give me a bit more context / information. What does this method do? Perhaps a sample usage?

If you are consuming data from a stream, there are "WithLengthPrefix" versions to automate limiting to discreet messages, or I believe the method to just read the next length from the stream is on the public API.

If you want to get a length in place of serializing, then currently I suspect the easiest option might be to serialize to a dummy stream and track the length. Oddly enough, an early version of protobuf-net did have "get the length without doing the work" methods, but after discussion on the protobuf-net I removed these. The data serialized is still tracked, obviously. However, because the API is different than the binary data length for objects is not available "for free".

If you clarify what the use-case is, I'm sure we can make it easily available (if it isn't already).


Re the comment; that is what I suspected. Because protobuf-net defers the binary translation to the last moment (because it is dealing with regular .NET types, not some self-generated code) there is no automatic way of getting this value without doing the work. I could add a mechanism to let you get this value by writing to Stream.Null? but if you need the data anyway you might benefit from just writing to MemoryStream and checking the .Length in advance of copying the data.

Marc Gravell
The Message::ByteSize() method returns the serialized size of the message and all it's data including sub-messages. I was looking for a similar feature to assign buffers ahead of the SerializeWithLengthPrefix() call but as an alternative could let the MemoryStream handle the expanding buffer and use the ToArray() call to get a buffer for the networking code.
Sébastien Taylor
@Sébastien Taylor - I'll update...
Marc Gravell