栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Google Protocol Buffer 使用入门

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Google Protocol Buffer 使用入门

首先在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
#include
#include
#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
#include
#include
#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"< 
二、编译 
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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/864319.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号