- 先寫一個文件尾綴爲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.