Google ProtoBuf C++ Example

SerializeToString & SerializeToArray

  1. syntax = "proto3";
  2.  
  3. package test;
  4.  
  5. message People {
  6.   string name = 1;
  7.   int32 age = 2;
  8.   int32 steps = 3;
  9. }
protoc Usage :
  1. water@waters-MacBook-Pro:~/Documents/GitHub/CppQt5/TestProtobuf$ protoc --cpp_out=. people.proto
  2. water@waters-MacBook-Pro:~/Documents/GitHub/CppQt5/TestProtobuf$ ls people.p*
  3. people.pb.cc people.pb.h  people.proto
  1. #include <iostream>
  2.  
  3. #include "people.pb.h"
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.     test::People pep;
  8.     pep.set_name("heheda");
  9.     pep.set_age(5);
  10.     pep.set_steps(1304);
  11.  
  12.     std::string buff;
  13.     pep.SerializeToString(&buff);
  14.  
  15.     test::People pep2;
  16.     pep2.ParseFromString(buff);
  17.  
  18.     std::cout << pep2.name() << std::endl;
  19.     std::cout << pep2.age() << std::endl;
  20.     std::cout << pep2.steps() << std::endl;
  21.  
  22.     int data_len = pep.ByteSize();
  23.     unsigned char data[1024] = "\0";
  24.     pep.SerializeToArray(data, data_len);
  25.     for(auto i = 0; i < data_len; i ++)
  26.         printf("%02X ", data[i]);
  27.     printf("\n");
  28.  
  29.     test::People pep3;
  30.     pep3.ParseFromArray(data, data_len);
  31.  
  32.     std::cout << pep3.name() << std::endl;
  33.     std::cout << pep3.age() << std::endl;
  34.     std::cout << pep3.steps() << std::endl;
  35.  
  36.     return 0;
  37. }

Leave a Reply

Your email address will not be published. Required fields are marked *