Back to TILs

C++ protobuf

Table of contents

Prototype

syntax = "proto2";
message Sensor {
  required string name = 1;
  required double temperature = 2;
  required int32 humidity = 3;

  enum SwitchLevel {
    CLOSED = 0;
    OPEN = 1;
  }
  required SwitchLevel door = 5;
}

Makefile

GRPC_CPP_PLUGIN = grpc_cpp_plugin
GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)`
%.grpc.pb.cc: %.proto
	protoc --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $<

%.pb.cc: %.proto
	protoc --cpp_out=. $<

Fill the object parameters.

  Sensor sensor;
  sensor.set_name("Laboratory");
  sensor.set_temperature(23.4);
  sensor.set_humidity(68);
  sensor.set_door(Sensor_SwitchLevel_OPEN);

Serialize to a file

  ofstream ofs("sensor.data", std::ios_base::out | std::ios_base::binary);
  sensor.SerializeToOstream(&ofs);
  ofs.close();

Parse parameters from file

  Sensor sensor2;
  ifstream ifs("sensor.data", ios_base::in | ios_base::binary);
  sensor2.ParseFromIstream(&ifs);

  cout << "Temperature: " << sensor2.temperature() << endl;
  cout << "Humidity: " << sensor2.humidity() << endl;
  cout << "Door: " << sensor2.door() << endl;

Possible output

Temperature: 23.4
Humidity: 68
Door: 1