protocol buffer 安裝與使用
1、下載protocol buffer
測試版本:protobuf-2.5.0.tar.gz
2、解壓並安裝,執行以下命令
tar -zxvf protobuf-2.5.0.tar.gz
./configure
make check
make install
3、書寫 .proto文件
package lm;
message helloworld
{
required int32 id = 1;
required string str = 2 ;
optional int32 opt = 3;
}//這是proto2的書寫規則,如果需要使用grpc則應使用proto3的書寫規則,參考網址https://developers.google.com/protocol-buffers/docs/proto3#simple
編譯形成 .cc、.h文件,執行命令:
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/test.proto
假設 proto 文件存放在 $SRC_DIR 下面,您也想把生成的文件放在同一個目錄下
如圖:
4、編寫writer和reader文件
writer文件:
#include "test.pb.h"
#include <iostream>
#include <fstream>
using namespace std ;
int main(void)
{
lm::helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
// Write the new address book back to disk.
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output)) {
cerr << "Failed to write msg." << endl;
return -1;
}
return 0;
}
reader文件:
#include "test.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
void ListMsg(const lm::helloworld & msg) {
cout << msg.id() << endl;
cout << msg.str() << endl;
}
int main(int argc, char* argv[]) {
lm::helloworld msg1;
{
fstream input("./log", ios::in | ios::binary);
if (!msg1.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
}
ListMsg(msg1);
}
5、編譯運行,形成writer,reader等exe文件
g++ test.pb.cc writer.cc -o writer -lprotobuf
g++ test.pb.cc reader.cc -o reader -lprotobuf
執行writer,執行reader,結果如圖: