protocol buffer 安装与使用

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、编写writerreader文件

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、编译运行,形成writerreaderexe文件

 g++ test.pb.cc writer.cc -o writer -lprotobuf

 g++ test.pb.cc reader.cc -o reader -lprotobuf

执行writer,执行reader,结果如图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值