protobuf简单使用

1、sudo apt-get install protobuf-compiler2.编写简单proto文件syntax = "proto2" ; //表明使用protobuf的编译器版本为v2,目前最新的版本为v3namespace{optional string name = 1 ;optional int32 age = 2 ;optional int32 xxx = 3 ; //xxx 代表任意字段名称,为api 举例方便}message VehicleSignal {enum.
摘要由CSDN通过智能技术生成

1、sudo apt-get install protobuf-compiler

2.编写简单proto文件
syntax = "proto2" ; //表明使用protobuf的编译器版本为v2,目前最新的版本为v3 namespace
{
optional string name = 1 ;

optional int32 age = 2 ;
optional int32 xxx = 3 ; //xxx 代表任意字段名称,为api 举例方便
}
message VehicleSignal {
enum TurnSignal {
TURN_NONE = 0 ;
TURN_LEFT = 1 ;
TURN_RIGHT = 2 ;
};
optional TurnSignal turn_signal = 1 ;
optional bool high_beam = 2 ;
optional bool low_beam = 3 ;
optional bool horn = 4 ;
optional bool emergency_light = 5 ;
}

3.编译

定义proto文件之后需要用protobuf提供的编译工具将proto文件编译成不同语言的源码,此处使用C++。

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

4.简单的测试代码
#include <stdio.h>
#include <iostream>
#include <string

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Protocol Buffers(简称 Protobuf)是一种语言无关、平台无关、可扩展的序列化数据格式,它可以用于数据存储、通信协议等领域。Protobuf 是 Google 公司开发的,它的主要优点是高效、轻量、可扩展。 下面是 Protobuf 的详细使用方法: 1. 安装 Protobuf 首先,需要安装 Protobuf 编译器。可以从官网下载安装包,也可以使用包管理工具进行安装。以下是在 Ubuntu 上使用 apt-get 进行安装的示例: ``` $ sudo apt-get install protobuf-compiler ``` 2. 定义 Protobuf 文件 Protobuf 使用 .proto 文件来定义数据结构。以下是一个简单的示例: ``` syntax = "proto3"; message Person { string name = 1; int32 age = 2; repeated string email = 3; } ``` 上面的示例定义了一个名为 Person 的消息类型,它包含三个字段:name、age 和 email。其中,name 和 age 是必需的字段,而 email 是可重复的字段。 3. 编译 Protobuf 文件 使用 Protobuf 编译器将 .proto 文件编译成目标语言的代码。以下是在 Linux 上使用命令行编译的示例: ``` $ protoc --proto_path=./proto --cpp_out=./src ./proto/person.proto ``` 上面的示例将 ./proto 目录下的 person.proto 文件编译成 C++ 代码,并将生成的代码存放在 ./src 目录下。 4. 序列化和反序列化 使用生成的代码进行序列化和反序列化操作。以下是一个示例: ```c++ #include "person.pb.h" #include <iostream> #include <fstream> using namespace std; int main() { // 创建一个 Person 对象 Person person; person.set_name("Tom"); person.set_age(20); person.add_email("tom@example.com"); person.add_email("tom@gmail.com"); // 将 Person 对象序列化到文件中 fstream output("person.bin", ios::out | ios::binary); person.SerializeToOstream(&output); output.close(); // 从文件中读取序列化的 Person 对象 fstream input("person.bin", ios::in | ios::binary); Person person2; person2.ParseFromIstream(&input); input.close(); // 输出读取到的 Person 对象的信息 cout << "name: " << person2.name() << endl; cout << "age: " << person2.age() << endl; for (int i = 0; i < person2.email_size(); i++) { cout << "email: " << person2.email(i) << endl; } return 0; } ``` 上面的示例将创建一个 Person 对象,并将其序列化到文件中。然后,从文件中读取序列化的 Person 对象,并输出其信息。 以上就是 Protobuf 的详细使用方法。需要注意的是,每个目标语言的生成代码可能会有所不同。因此,在使用 Protobuf 时,需要查看官方文档,了解相关的生成代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值