protobuf简介和使用

本文介绍了Google开发的数据描述语言Protocol Buffers的特点与优势,并详细展示了如何在C++环境中进行安装、编写数据描述文件、编译及测试程序的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Protocol Buffers简介

Protocol Buffers (ProtocolBuffer/ protobuf )是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。现阶段支持C++、JAVA、Python等三种编程语言。

2.protobuf相比Xml的优点

•更简单
•数据描述文件只需原来的1/10至1/3
•解析速度是原来的20倍至100倍
•减少了二义性
•生成了更容易在编程中使用的数据访问类
3.安装
yum -y install  protobuf-compiler protobuf-static protobuff protobuf-devel
4.使用
vi helloworld.proto
 
输入下面的数据:

message helloworld {

     required int32 id = 1; // ID

     required string str = 2; // str

}

5.编译 .proto

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

protoc -I=. --cpp_out=. ./helloworld.proto

命令将生成:

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

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

 

6.测试程序

#include "helloworld.pb.h" //包含生成的头文件
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) { 
    helloworld msg; 
    msg.set_id(101); 
    msg.set_str("hello"); 
    // 序列化消息
    char buff[1024] = {0};
    msg.SerializeToArray(buff, 1024);
    //解析消息
    helloworld msgread;
    msgread.ParseFromArray(buff, 1024);
    cout << msgread.id() << endl; 
    cout << msgread.str() << endl; 
}

  

  

 7.编译运行

      g++ -o main  main.cpp helloworld.pb.cc -lprotobuf -lpthread

      ./main

 

转载于:https://www.cnblogs.com/moxiaopeng/p/4988793.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值