初探proto和protobuf

初探

protobuf是一种类似xml生成java对象的技术,经过protoc编译.proto文件为.h和.cc文件供给C++调用。是一种数据对象生成方式,.proto定义对象的个格式。

  • data.proto
syntax = "proto3";
package train_set;
message PhoneNumber {
    string number = 1;
    int32 type = 2 ;
}
message Person {
    string name = 1;
    int32 id = 2;
    string email = 3;
    repeated PhoneNumber phone = 4;
}

执行

 protoc --cpp_out=. data.proto

生成
在这里插入图片描述

.cc和.h两个文件,在cpp中

# include <iostream>
# include <fstream>
# include <string>
# include "data.pb.h"
using namespace std;
int main(int argc,char *argv[]){
    train_set::Person person = train_set::Person();
    person.set_name("rrr");
    for(int i=0;i<10;++i){
        train_set::PhoneNumber * phone = person.add_phone(); //嵌套,先add再set
        phone->set_number("123");
    }
    fstream out = fstream("ddd.model",ios::out |ios::trunc| ios::binary);
    person.SerializeToOstream(&out);
    out.close(); //序列化后记得关闭流
    out.clear();
    // cout<<person.SerializeAsString()<<endl;
    fstream in = fstream("ddd.model",ios::in | ios::binary); // 反序列化
    train_set::Person person2;                                          
    person2.ParseFromIstream(&in);
    // cout<<person2.SerializeAsString()<<endl;
    cout<<person2.name()<<endl;
    for(int i=0;i<person2.phone_size();++i){
        train_set::PhoneNumber phone = person2.phone()[i];
        cout<<phone.number()<<endl;
    }
    in.close();
    in.clear();
    return 0;
}

编译

g++ data.pb.cc protobuf_test.cpp -o aa.out -std=c++11 -I /usr/local/include/ -L /usr/local/lib/ -lprotobuf -lpthread

生成
在这里插入图片描述

运行

./aa.out

输出

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值