谷歌 Google ProtoBuf用法实例

这里贴一个介绍贴http://blog.csdn.net/hailong0715/article/details/52016682

这里就介绍怎么安装的了,安装caffe的时候一起安装的,这里介绍一下怎么用这个库,caffe用他来当数据传输说明他很快

新建一个proto定义数据传输的结构,这个和ros上数据传输很像

syntax = "proto2";
package caffe; //域名
message Person {  
  required string name = 1;  
  required int32 age = 2;  
  optional string email = 3;  

  enum PhoneType {  
    MOBILE = 0;  
    HOME = 1;  
    WORK = 2;  
  }  
  
  message PhoneNumber {  
    required string number = 1;  
    optional PhoneType type = 2 [default = HOME];  
  }  
  
  optional PhoneNumber phone = 4; 
  
}  

package 指的是域名,就是std一样

write.cpp

#include <iostream>  
#include <fstream>  
#include "caffe.pb.h"  
  
using namespace std;  
using namespace caffe;  
  
int main()  
{  
    Person person;  
  
    person.set_name("flamingo");     
    person.set_age(18);   
    person.set_email("majianfei1023@gmail.com");  
    person.mutable_phone()->set_number("135525");
    
    // Write  
    fstream output("./log", ios::out | ios::trunc | ios::binary);  
  
    if (!person.SerializeToOstream(&output)) {  
        cerr << "Failed to write msg." << endl;  
        return -1;  
    }  
  
    //system("pause");  
    return 0;  
}  

上面的修改其实我是看他生产的caffe.pb.h里面定义的函数,发现有这些函数可以直接用的

read.cpp

#include <iostream>  
#include <fstream>  
#include "caffe.pb.h"  
  

using namespace std;  
using namespace caffe;  
  
void PrintInfo(const Person & person) {   
    cout << person.name() << endl;   
    cout << person.age() << endl;   
    cout << person.email() << endl;  
    cout << person.phone().number() << endl; 
    cout << person.phone().type() << endl; 

}   
  
int main()  
{  
    Person person;    
  
    fstream input("./log", ios::in | ios::binary);  
      
    if (!person.ParseFromIstream(&input)) {  
        cerr << "Failed to parse address book." << endl;  
        return -1;  
    }  
  
    PrintInfo(person);  

    return 0;  
}


然后编译,加入库就好了

protoc --cpp_out=./ caffe.proto   #在当前目录生成.h和.cc
g++ write.cpp caffe.pb.cc -o write -lprotobuf
g++ read.cpp caffe.pb.cc -o read -lprotobuf




  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值