protobuf在windows 的Qt和ubuntu的Qt上的使用(二)

一、使用环境

系统:ubuntu 14.04
Qt版本:5.2.1
protobuf版本:3.8.0

二、在ubuntu上安装protobuf库

  1. protobuf开源地址:https://github.com/protocolbuffers/protobuf
  2. 找到想要3.8.8版本,在ubuntu上下载protobuf源码:https://github.com/protocolbuffers/protobuf/tags
  3. 将protobuf源码压缩包解压到指定目录;
  4. 打开一个终端,切换当前目录到protobuf解压文件夹下;
  5. 然后在终端依次执行以下命令:
    在这里插入图片描述
    当检查protoc的版本时输出:在这里插入图片描述
    证明protobuf库安装成功了,后面就可以在我们的代码中使用protobuf库。

三、编写proto文件

message.proro定义如下:

syntax = "proto3";
package tutorial;

message Person {
  string name = 1;
  int32 id = 2;
  string email = 3;
  string phone = 4;
}

proto文件的语法见其他相关的资料。

四、使用protoc工具生成proto文件对应的操作类

在终端键入如下命令:protoc --cpp_out=. message.proto回车,生成对应的message.pb.h和message.pb.cc类文件。在生成的类中,每个proto文件的字段都有相对应的类成员变量对应,还有对应set/get类成员函数来操作这些成员变量。后面就可以创建这个类对象,来操作(读写)类成员变量了。

五、创建一个Qt工程, 应用protobuf库

先在Qt工程文件.pro中把protobuf库和protobuf的头文件包含进我们创建的工程:
在这里插入图片描述
把message.pb.h和message.pb.cc加入Qt工程,然后实现序列化:

#include <message.pb.h>
using namespace tutorial;
int main(int argc, char *argv[]) {
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    Person person;
    person.set_id(9527);
    person.set_name("zhouxingxing");
    person.set_phone("110");

    std::string filename = "person.bin";
    std::fstream output(filename, std::ios::out | std::ios::trunc | std::ios::binary);
    if (!person.SerializeToOstream(&output)) {
          std::cerr << "Failed to write person." << std::endl;
      }
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}

然后反序列化:

#include <message.pb.h>
using namespace tutorial;
int main(int argc, char *argv[]) {
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    Person person;
    std::string filename = "person.bin";
    fstream input(filename, ios::in | ios::binary);
       if (!person.ParseFromIstream(&input)) {
         cerr << "Failed to parse person." << endl;
         return -1;
       }
    cout << "id:" << person.id() << endl;
    cout << "name:" << person.name() << endl;
    cout << "phone:" << person.phone() << endl;
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}

反序列化的结果为:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值