Protocol Buffers


Overview


  • Protocol Buffer provides a method of serialization structured data.
  • It provides a very flexible method and high performance.
  • It supports so many languages such as c++, c#, go, java and python, and so on.

Sample

  • hello.proto
syntax ="proto2";
package tutorial;
message Person
{
required string name = 1;
required int32 id= 2;
optional string email=3;
}

  • build
    • protoc -I=. --cpp_out=./cpp hello.proto
    • hello.pb.h and hello.pb.cpp are generated.

  • main.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "cpp/hello.pb.h"
using namespace std;
using namespace tutorial;
void toFile()
{
Person man;
ofstream file("person.db");
man.set_name("mhkang");
man.set_id(100);
man.set_email("freehuni@hanmail.net");
///man.SerializePartialToOstream(&file);
man.SerializeToOstream(&file);
}
void fromFile()
{
Person man;
ifstream file("person.db");
man.ParseFromIstream(&file);
cout << "name:" << man.name() << endl;
cout << "id:" << man.id() << endl;
cout << "email:" << man.email() << endl;
}
int main()
{
toFile();
fromFile();
return 0;
}

  • CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
SET(PROJECT_NAME "hello")
PROJECT(${PROJECT_NAME})

ADD_DEFINITIONS( -D_POSIX -D_LARGEFILE64_SOURCE=1 -DSIZE_64BIT_SUPPORT -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64)

INCLUDE_DIRECTORIES(/home/mhkang/workspace/samples/opensource/protobuf/hello/cpp)

ADD_EXECUTABLE(${PROJECT_NAME}
./main.cpp
./cpp/hello.pb.cc
)

TARGET_LINK_LIBRARIES(${PROJECT_NAME} protobuf)


  • build
    • cmake .
    • make

Reference Sites


댓글