Sunday, June 5, 2016

Xamarin & protobuf Hello, world

I played with Xamarin and wanted to use protobuf. Here is the example of running a basic "Hello, world".

Step 0.
Add Google.ProtocolBuffersLite via NuGet.

Step 1.
Create Messages.proto
option optimize_for = LITE_RUNTIME;

message Hello {
  required int32 version = 1;
  optional string message = 2;
}

The first line with lite runtime is important – you would get multiple errors of missing references without it. I actually spent hours playing around before Jon Skeet gave me a golden hint.

Step 2.
from packages\Google.ProtocolBuffersLite.2.4.1.555\tools\ run
ProtoGen.exe messages.proto
and add the generated Messages.cs to the project.

That's it.You can (de)serialize messages as the following:
var b = Hello.CreateBuilder();
b.Version = 1;
b.Message = "Hello, world";
Hello h = b.Build(); // now we have the object

var ms = new MemoryStream();
h.WriteDelimitedTo(ms); // serialize

var ms2 = new MemoryStream(ms.ToArray());
var h2 = Hello.ParseDelimitedFrom(ms2); // and get it back

These are not best practices, of course. Just a basic thing to start with.

No comments:

Post a Comment