c/c++ protobuf 序列化 反序列化

一:序列化

        1.fstream

// Write the new address book back to disk.

fstream output(argv[1], ios::out | ios::trunc | ios::binary);

if (!address_book.SerializeToOstream(&output)) {

cerr << "Failed to write address book." << endl;

    return -1;

}

        2.char*

方法二:

int size = address_book.ByteSize();

void *buffer = malloc(size);

address_book.SerializeToArray(buffer, size);


方法三:

使用ostringstream ,

std::ostringstream stream;

address_book.SerializeToOstream(&stream);

string text = stream.str();

char* ctext = string.c_str();

二:反序列化

        1.fstream

    // Read the existing address book.

    fstream input(argv[1], ios::in | ios::binary);

    if (!input) {

      cout << argv[1] << ": File not found.  Creating a new file." << endl;

    } else if (!address_book.ParseFromIstream(&input)) {

      cerr << "Failed to parse address book." << endl;

      return -1;

    }

        2.char*

address_book.ParseFromArray(char*)

三:repeated 使用

        1.添加数据

        

    mLocationInfo = mLocation.add_data();
    if(!mLocationInfo)
    {
        return;
    }

    mLocationInfo->set_cardid(cardID);
    mLocationInfo->set_sleep(speed);
    mLocationInfo->set_longitude(longitude);
    mLocationInfo->set_latitude(latitude);
    mLocationInfo->set_datatime(time);

        2.解析数据      

message LocationInfo{
    uint32 CardID=1;        
    double Longitude=2;    
    double Latitude=3;      
    float Sleep =4;  
    string Datatime=5;      
}
message Location{
    string CMD=1;   
    uint32 CarID=2; 
    repeated LocationInfo Data=3;
}
    Card::Location mLocation;
    if (mLocation.ParseFromArray(data, len) == false)//反序列化
    {
        return "ParseFromArray fail";
    }

    for (int nLoop = 0; nLoop < mLocation.data_size(); nLoop++)
    {
        Card::LocationInfo mInfo = mLocation.data(nLoop);//获取对应LocationInfo数据
    }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值