Google Protocol Buffer 使用入门

本文档详细介绍了如何在Linux环境中安装protobuf,并提供了C++代码示例,展示如何读写protobuf消息。首先,通过protoc编译器生成C++代码,然后分别编译reader和writer程序,最后运行程序实现protobuf消息的序列化和反序列化操作。
摘要由CSDN通过智能技术生成

首先在Linux下安装protobuf,然后开始使用

一、编写相关代码

//my.proto
syntax = "proto2";
package my;
message helloworld 
{ 
   required int32     id = 1;  // ID 
   required string    str = 2;  // str 
   optional int32     opt = 3;  //optional field 
}
//reader.cpp
#include<iostream>
#include<string>
#include<fstream>
#include "my.pb.h"
using namespace std;

void ListMsg(const my::helloworld & msg) { 
  cout << msg.id() << endl; 
  cout << msg.str() << endl; 
} 
  
int main(int argc, char* argv[]) { 
 
  my::helloworld msg1; 
  
  { 
    fstream input("./hhh.txt", ios::in | ios::binary); 
    if (!msg1.ParseFromIstream(&input)) { 
      cout << "Failed to parse address book." << endl; 
      return -1; 
    } 
  } 
  
  ListMsg(msg1); 
  return 0;
}
//writer.cpp
#include<iostream>
#include<string>
#include<fstream>
#include "my.pb.h"
using namespace std;
 
int main()
{
    string str = "hello";
  my::helloworld msg1; 
  msg1.set_id(101); 
  msg1.set_str(str); 
  // Write the new address book back to disk. 
  fstream output("hhh.txt", ios::out | ios::trunc | ios::binary); 
  cout<<"hhh"<<endl;
  if (!msg1.SerializeToOstream(&output)) { 
      cout << "Failed to write msg." << endl; 
      return -1; 
  }         
  return 0; 
}

二、编译

protoc --proto_path=. --cpp_out=. my.proto
g++ my.pb.cc reader.cpp -o read -lprotobuf -std=c++11 -lpthread
g++ my.pb.cc writer.cpp -o writer -lprotobuf -std=c++11 -lpthread

现在文件夹下的文件如图:

 

三、运行

四、原理参考

Protobuf序列化原理_钟离默的博客-CSDN博客

Encoding  |  Protocol Buffers  |  Google Developers

Protobuf 使用介绍及原理: Protobuf 使用介绍及原理 (gitee.com)

 

参考:C++ Generated Code  |  Protocol Buffers  |  Google Developers

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值