本文主要讲解protobuf的基本用法(caffe使用protobuf所用到的语法)
protobuf简介
protobuf功能是把某种数据结构的信息以某种格式保存起来。它主要用于文件存储以及传输协议格式等场合。protobuf的优点主要有
- 性能好/效率高
- 向前兼容和向前兼容
- 支持多种语言
protobuf简单用法
假如我们有一个问题是关于:存储一个人的名字(name)以及唯一表示符(id)和邮箱(email)以及它的电话号码(number)和此电话号码所在的类型(PhoneType)。并且需要将其保存在二进制文件中或者txt文件中,如果需要还需要将其从二进制文件中或者txt文件中读取,我们如何使用protobuf去实现它呢?
- 首先我们需要创建一个caffe.proto文件,文件中的内容为:
#caffe.proto
syntax = "proto2";
package caffe;
message Person {
required string name = 1;
required int32 id = 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];
}
repeated PhoneNumber phone = 4;
}
syntax声明使用的语法规则,proto2相当于python3和python2的区别,所以为了正确解析,我们需要声明正确的proto版本。
message表示消息,相当于c++中的一个类Person。required表示必须字段,而optional表示可选字段,repeated表示可重复字段(每一个人都有多个电话号码),这些关键字紧接着的关键字(string int32 etc.)为我们声明的变量的类型。
- 第二部需要创建一个主函数(main.cpp),主要功能是演示序列化一个Person类,并且写入文件中,main.cpp文件的主要内容为:
#include <iostream>
#include <string>
#include "caffe.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <glog/logging.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <fcntl.h>
#include <unistd.h>
#include <fstream>
const int kProtoReadBytesLimit = INT_MAX;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::p