protobuffer

caffe 里面贯穿始终的文件格式就是protobuffer和glog了,不得不佩服,google确实很牛啊,恭维的话不说,熟悉一下protobuffer吧。其中官方文档什么的,网上搜吧,还有一系列别人在ubuntu和windows下的使用。把caffe中的代码粘贴下来如下:




//读取保存为text文档的proto文件,读进来,并通过Parse解析。
void ReadProtoFromTextFile(const char* filename,
    ::google::protobuf::Message* proto) {
  int fd = open(filename, O_RDONLY);
  CHECK_NE(fd, -1) << "File not found: " << filename;
  FileInputStream* input = new FileInputStream(fd);
  CHECK(google::protobuf::TextFormat::Parse(input, proto));
  delete input;
  close(fd);
}




//把proto写到文件,文件是text格式的。
void WriteProtoToTextFile(const Message& proto, const char* filename) {
  int fd = open(filename, O_WRONLY);
  FileOutputStream* output = new FileOutputStream(fd);
  CHECK(google::protobuf::TextFormat::Print(proto, output));
  delete output;
  close(fd);
}




//读proto,其中proto的保存格式是binary格式文件。
void ReadProtoFromBinaryFile(const char* filename, Message* proto) {
  int fd = open(filename, O_RDONLY);
  CHECK_NE(fd, -1) << "File not found: " << filename;
  ZeroCopyInputStream* raw_input = new FileInputStream(fd);
  CodedInputStream* coded_input = new CodedInputStream(raw_input);
  coded_input->SetTotalBytesLimit(536870912, 268435456);




  CHECK(proto->ParseFromCodedStream(coded_input));




  delete coded_input;
  delete raw_input;
  close(fd);
}




//将proto保存到文件,文件的序列化格式是binary的
void WriteProtoToBinaryFile(const Message& proto, const char* filename) {
  fstream output(filename, ios::out | ios::trunc | ios::binary);
  CHECK(proto.SerializeToOstream(&output));
}




从代码可以看到,提供了两种格式,一种是文档格式的,一种是二进制格式的。其中值得注意的是几个函数,
ZeroCopyInputStream ,相应的有ZeroCopyOutputStream //避免进行内存的拷贝 具体参考:http://name5566.com/2633.html,https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.io.zero_copy_stream
CodedInputStream  相应CodedOutputStream//,正如上面代码写的,用来定义不同长度的解析,理解的可能不太对,具体可参见:https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.io.coded_stream?hl=zh-CN
未完待续,儿子哭闹了,要哄我家小祖宗碎觉了。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值