In the following code i want to use a predefined protobuf message in c#. I found that I was able to write and use the method to take a method that has been created and make a byte[]:
ContainerMessage containerMessage = new ContainerMessage();
containerMessage.Type = CommandType.Connect;
containerMessage.Connect = new Connect();
containerMessage.Connect.ClientName = "TemporaryClientName";
byte[] stream = new byte[containerMessage.CalculateSize()];
using (Google.Protobuf.CodedOutputStream outstream = new Google.Protobuf.CodedOutputStream(stream))
{
containerMessage.WriteTo(outstream);
}
This works as expected and i can inspect the message and the values are as expected as are the values in the byte[]. But if I try to Deserialize even this simple byte[] that i have just created:
using (Google.Protobuf.CodedInputStream instream = new Google.Protobuf.CodedInputStream(stream))
{
instream.ReadMessage(containerMessage);
}
It fails with:
An unhandled exception of type 'Google.Protobuf.InvalidProtocolBufferException' occurred in Google.Protobuf.dll
Additional information: Protocol message contained an invalid tag (zero).
Is this way of deserializing from a byte[] correct for protobuf?
The Protobuf Definition is:
message ContainerMessage {
CommandType type = 1;
bool commandSuccess = 2;
oneof message {
Connect connect = 3;
}
}
enum CommandType {
START = 0;
CONNECT = 2;
}
message Connect {
string ClientName = 1;
uint32 PushPullPort = 2;
}
And the CS file is generated with the command line:
protoc.exe -I=%CD% --csharp_out=..\GeneratedCsMessaging\ Connect.proto
WriteTagmethod. This might explain the upcoming error for you having an invalid tag. As both CodedInputStream and CodedOutputStream state "This class is generally used by generated code" I'd think that both aren't generally meant to be used outside of the generated classes. - TornadowarnungCodedOutputStream(my experience is with protobuf-net, where you just callSerializer.Serialize(stream, obj), but you can check whether thebyte[]data is valid easily here: protogen.marcgravell.com/decode (you can also use protogen.marcgravell.com to quickly generate C# for either protobuf-net or the Google version from your schema, for example: protogen.marcgravell.com/#g54f761a063bbd74e0617b85468a8b06a) - Marc Gravellusing Google.Protobuf;so i couldn't understand that you can pass a MemoryStream straight to the Google protobuf. If you add your answer and include this, i will accept it. - Fantastic Mr Fox