This post is meant as a brief introduction that will point you in the right direction rather than an exhaustive tutorial. Here we go…
Have you ever had to write code that serialized structured data into an efficient binary format, to be later saved to disk or sent over the network? Do you remember how difficult and time consuming it was? Haven’t you wished there was a standard C++ library to do it instead of reinventing the wheel? Well, today is your lucky day.
Say hello to Google’s Protocol Buffers! It is a highly portable (and free!) library that allows you to define near arbitrary (numerical, strings, structures, lists, vectors, maps, you name it) data formats and easily serialize and deserialize them into a platform portable binary format. Why not use XML you may ask? How about 3 to 10 times smaller output, and 20 to 100 times faster serialization and deserialization just to name a few.
Let’s start by defining a protocol buffer file that defines a “
Person” data structure:
syntax = "proto2";
required string name = 1;
required int32 dob = 2;
optional string email = 3;
Save that to protobuf.proto file and let’s compile it using the protoc code generator; yes, Protocol Buffers is a code generator; it takes as input a .proto file and spits out C++ classes (it can also produce code in C#, Java, JS, ObjC, PHP, Python, and Ruby).
protoc basic usage:
protoc -I=. –cpp_out=. protobuf.proto
The above command will produce 2 files: protobuf.pb.h and protobuf.pb.cc. Let’s now write a simple program that creates, serializes, and deserializes our data structure using the generated classes:
using namespace std;
int main(int argc, char** argv)
cout << "Name = " << p2.name() << endl;
cout << "DOB = " << p2.dob() << endl;
cout << "EMail = " << p2.email() << endl;
This code is pretty self explanatory. We create, set and serialize one data structure of type
data::Person, then deserialize it into another. The output is what we would expect.
Name = Martin Vorbrodt
DOB = 19800830
EMail = firstname.lastname@example.org
That’s enough of an introduction. I hope you will read up on Protocol Buffers and realize the enormous potential of this library. Happy coding!
P.S. As always, the complete source and build files are available at my GitHub.