- 先写一个文件尾缀为proto文本文件,message.proto,内容如下:
syntax = "proto3";
//指定使用的proto版本,这里是protobuf3
//import "user.proto";
//这里可以包含其他proto文件,可以用user文件中的message定义字段
//生成的message.pb.h中会有#include "user.pb.h"一句代码
//相当于自动include其他proto生成的头文件,自然也可以
//使用user中的类型定义message.proto中的某个类的字段
package chat.proto.message;
//生成c++代码后,相当于嵌套三层的namespace,即chat::proto::message
//每一个message对应即将生成源文件中的一个类,即chat::proto::message::LoginRequest
message LoginRequest{
bytes name = 1; //bytes和string使用没有什么区别,这里也可以使用string
bytes pwd = 2;
}
message LoginReesponse{
int32 errcode = 1;
bytes errmsg = 2;
bool success = 3;
}
- 然后使用protoc工具,将上面的proto文件生成对应的头文件和源文件:
protoc message.proto --cpp_out=./
执行完成后将生成两个文件,分别是message.pb.h和message.pb.cc
protoc:用来生成源码的转换工具;
message.proto:就是我们要将哪些proto转换成源文件
--cpp_out:转换成c++代码
./:生成的message.pb.cc和message.pb.h就存放在当前文件夹
- 序列化:将数据转换成字节流;
- 反序列化:将数据从字节流中提取转换出来
- 使用实例:
#include <iostream>
#include <string>
#include "message.pb.h"
using namespace std;
using namespace chat::proto::message;
int main(){
LoginRequest lre;
lre.set_name("king");
lre.set_pwd("1234567");
//数据序列化,序列化成字节流/字符流
string str("xxx");
cout<<str.c_str()<<endl;
lre.SerializeToString(&str);
cout<<str.c_str()<<endl; //实际开发可以通过网络发送出去
//bool SerializeToString(std::string* output) const;
//数据的反序列化,将数据从字节流中解析出来
LoginRequest lrf;
lrf.ParseFromString(str);
cout<<lrf.name()<<endl;
cout<<lrf.pwd()<<endl;
//inline bool ParseFromString(const std::string& data)
return 0;
}
g++ main.cpp message.pb.cc user.pb.cc -lprotobuf
./a.out
output:
xxx
king1234567
king
1234567
- protobuff两个重要常用的方法:
// Serialize the message and store it in the given string. All required
// fields must be set.
bool SerializeToString(std::string* output) const;
将一个proto对象序列化成字节流,存储在字符串output中。成功返回true.
inline bool ParseFromString(const std::string& data);
将自已存放proto对象数据的字符串进行解析,也就是将数据从字符串中取出来。成功返回true.