linux前置条件
sudo apt-get install autoconf automake libtool curl make g++ unzip
最新包proto3 git下载地址,找到自己对应的语言
https://github.com/protocolbuffers/protobuf/releases/latest
编译protoc
./autogen.sh
./configure
make
sudo make install
如果想用已经编译好的,下载protoc开头的zip包就好
Mac下的方法更简单
brew install
使用方法
写一个简单的tutorial.proto
syntax = "proto3";
package tutorial;
message Test1 {
int32 a = 1;
}
protoc simple.proto --cpp_out=.
protoc simple.proto --python_out=.
protoc simple.proto --java_out=.
protoc simple.proto --js_out=.
protoc simple.proto --js_out=.
#include <iostream>
#include <fstream>
#include "tutorial.pb.h"
using namespace std;
int main(int argc, char const *argv[])
{
tutorial::Test1 t1;
t1.set_a(150);
cout << "t1.a = " << t1.a() << endl;
std::string message;
t1.SerializeToString(&message);
fstream f;
f.open("/tmp/pbuf", ios::out | ios::binary);
if(!f.is_open()) {
cout << "CANNOT OPEN /tmp/pbuf" << endl;
}
f << message;
f.close();
tutorial::Test1 t2;
t2.ParseFromString(message);
cout << "t2.a = " << t2.a() << endl;
return 0;
}
编译一下看看
g++ tutorial.pb.cc main.cc -std=c++11 $(pkg-config --libs protobuf)
编码方式
00000000: 0896 01