Google Protocol Buffer 介绍

Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 48,162 种报文格式定义和超过 12,183 个 .proto 文件。他们用于 RPC 系统和持续数据存储系统。

Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。

1.定义proto

				
 package lm; 
 message helloworld 
 { 
    required int32     id = 1;  // ID 
    required string    str = 2;  // str 
    optional int32     opt = 3;  //optional field 
 } 


2.编译proto为cpp文件

 protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto


生成两个文件

lm.helloworld.pb.h , 定义了 C++ 类的头文件

lm.helloworld.pb.cc , C++ 类的实现文件

3.生成、存储

 

				
 #include "lm.helloworld.pb.h"
…

 int main(void) 
 { 
  
  lm::helloworld msg1; 
  msg1.set_id(101); 
  msg1.set_str(“hello”); 
    
  // Write the new address book back to disk. 
  fstream output("./log", ios::out | ios::trunc | ios::binary); 
        
  if (!msg1.SerializeToOstream(&output)) { 
      cerr << "Failed to write msg." << endl; 
      return -1; 
  }         
  return 0; 
 } 


4.读取、反序列化

 

 #include "lm.helloworld.pb.h" 
…
 void ListMsg(const lm::helloworld & msg) { 
  cout << msg.id() << endl; 
  cout << msg.str() << endl; 
 } 
 
 int main(int argc, char* argv[]) { 

  lm::helloworld msg1; 
 
  { 
    fstream input("./log", ios::in | ios::binary); 
    if (!msg1.ParseFromIstream(&input)) { 
      cerr << "Failed to parse address book." << endl; 
      return -1; 
    } 
  } 
 
  ListMsg(msg1); 
  … 
 } 


5.其他常用函数

Message中常用函数:

 

bool	
SerializeToFileDescriptor(int file_descriptor) const;
Serialize the message and write it to the given file descriptor.

bool	
SerializeToOstream(ostream * output) const;
Serialize the message and write it to the given C++ ostream

bool	
SerializeToString(string * output) const;
Serialize the message and store it in the given string

bool	
ParseFromString(const string & data);
Parse a protocol buffer contained in a string

bool	
ParseFromIstream(istream * input);
Parse a protocol buffer from a C++ istream

bool	
ParseFromFileDescriptor(int file_descriptor);
Parse a protocol buffer from a file descriptor

重复字段的操作例子

 

message RowProto {
repeated string column = 1;
}
row_proto.add_column("123");//增加
row_proto.column(1);//取第一个
row_proto.column_size();//行个数


具体参考Google Protocol Buffer 的使用和原理Google API

原文地址:https://www.cnblogs.com/whuqin/p/4982018.html