Protobuf C++ 第一个例子

来源:互联网 发布:执行云计算的服务器 编辑:程序博客网 时间:2024/04/30 12:26

  • 新建一个proto文件
  • 生成C类
  • 编写Write函数
  • 编写Read函数
  • Main函数

新建一个.proto文件

假设已经配置好了Protobuf的C++的环境, 用一个最简单的例子来实验Protobuf工具.
新建一个hello.proto 文件

package lm;     // 相当于C++ 中的命名空间message helloworld    // 相当于数据库中一个表的名称{    required int32         id=1;   // 相当于数据库中不为空的字段    optional string        str=2;  // 相当于数据库中可空字段    enum PhoneType {               // 相当于表的默认值         MOBILE = 0;        HOME = 1;        WORK = 2;      }    message PhoneNumber {         // 嵌套表格        optional string number = 1;        optional PhoneType type = 2;      }    repeated PhoneNumber phones = 4;  // 重复对象(相当于数组)}

生成C++类

在CMD中输入:

protoc –proto_path=IMPORT_PATH –cpp_out=DST_DIR path/to/proto

对应输入文件夹 + 输出Cpp的文件夹 + Proto文件
要保证系统能找到protoc.exe 文件, 或者在protoc.exe 所在文件夹中运行

编写Write函数

将写入Protobuf中的对象写入到某个文件中:

bool writeBuf(string file_path){    lm::helloworld msg1;   // 包名::Message名     lm::helloworld::PhoneNumber *phone;  // 注意嵌套Message使用指针    msg1.set_id(100);    msg1.set_str("200");    phone = msg1.add_phones();    phone->set_number("12345");    phone->set_type(lm::helloworld_PhoneType_HOME);  // 注意Enum的调用方式(所有的默认值相当于C++中的Const对象, 所以直接使用类调用)    // Write the new address book back to disk.     fstream output(file_path, ios::out | ios::trunc | ios::binary);     if (!msg1.SerializeToOstream(&output)) {         cerr << "Failed to write msg." << endl;         return false;     }         return true;}

编写Read函数

读取文件中的Protobuf对象

// 输出数据void ListMsg(const lm::helloworld & msg) {     cout << msg.id() << endl;     cout << msg.str() << endl;     for (int i =0; i<msg.phones_size(); i++)    {        // 注意此时调用嵌套类中的值不是用的指针方式.        cout << msg.phones(i).number() << endl;    }} // 读取文件,写入到protobuf生成的类中bool readBuf(string file_path){    lm::helloworld msg1;    {         fstream input(file_path, ios::in | ios::binary);         if (!msg1.ParseFromIstream(&input)) {             cerr << "Failed to parse address book." << endl;             return -1;         }     }     ListMsg(msg1); }

Main函数

int main()  {      string path = "../test.log";    writeBuf(path);    readBuf(path);    return 0;  }  
0 0