首先在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<iostream>
#include<string>
#include<fstream>
#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<iostream>
#include<string>
#include<fstream>
#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"<<endl;
if (!msg1.SerializeToOstream(&output)) {
cout << "Failed to write msg." << endl;
return -1;
}
return 0;
}
二、编译
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
现在文件夹下的文件如图:
三、运行
四、原理参考
Encoding | Protocol Buffers | Google Developers
Protobuf 使用介绍及原理: Protobuf 使用介绍及原理 (gitee.com)
参考:C++ Generated Code | Protocol Buffers | Google Developers