How it works...

FlatBuffers is an external library that is not available in the Ubuntu repository of packages, which is why we need to download, build, and install it first. After the installation is done, we can use it in our application.

We use an existing application we created for the Using C++ lambdas for callbacks recipe as a starting point. In that application, we defined a structure, called Message, to represent a type of data we use for IPC. We are going to replace it with a new data type provided by FlatBuffers. This new data type will perform all the necessary serialization and deserialization transparently for us. 

We remove the definition of the Message struct from our code completely. Instead, we generate a new header file, called message_generated.h. This file is generated from the message.fbs FlatBuffers schema file. This schema file defines a structure with two integer fieldsx and y:

  x: int;
y: int;

This definition is identical to our preceding definition; the only difference is the syntaxFlatBuffers' schema uses a colon to separate field names from the field types.

Once message_generated.h is created by the flatc command invocation, we can use it in our code. We add the proper include as follows:

#include "message_generated.h"

The generated message is identical to the message structure we used before but as we discussed earlier, FlatBuffers stores data in serialized form and needs to deserialize it on the fly. That is why, instead of direct access to the data fields, we have to use the x() accessor method instead of just x and the y() accessor method instead of just y.

The only place we use direct access to the message data field is in the overridden operator<< operation. We add parentheses to turn direct field access into the invocation of the FlatBuffers getter methods:

  o << "(x=" << m.x() << ", y=" << m.y() << ")";

Let's build and run the application. We will see the following output:

The output is the same as for our custom message data type. With only a few modifications in our code, we migrated our messages to FlatBuffers. Now, we can run our publishers and subscribers on multiple computerswhich can have different architecturesand be sure that each of them interprets messages correctly. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.24.134