Protobuf简单例子

来源:互联网 发布:sql server distinct 编辑:程序博客网 时间:2024/05/21 07:54

1. 实例

可参考Protobuf的官网例子:
https://developers.google.com/protocol-buffers/docs/cpptutorial

第一步:设计Person对象的proto文件(person.proto),Protobuf编译器利用它生成C++文件(person.pb.h、person.pb.cc)

person.proto 文件

package Test;  message Person   {     required string name = 1;     required int32 id = 2;     optional string email = 3;  }  

第二步:通过protoc编译生成C++文件:

protoc -I=./ --cpp_out=./ ./person.proto

第三步:导入需要的头文件,源代码文件和库

第四步:写main.cpp的源文件

#include <iostream>#include <fstream>using namespace std;#include "person.pb.h"int main(){    // Verify that the version of the library that we linked against is    // compatible with the version of the headers we compiled against.    GOOGLE_PROTOBUF_VERIFY_VERSION;    Test::Person person;  //类型对象    person.set_id(101);    person.set_name("yvhqbat");    person.set_email("yvhbat@126.com");    cout << "person is "<<person.id() << ends << person.name() << ends << person.email() << endl;    string encode_str;    person.SerializeToString(&encode_str);  //序列化到字符串    cout << "the encode string is "<<encode_str << endl;    //输出到文件    string file_name("prototest.txt");    fstream output(file_name, ios::out | ios::trunc | ios::binary);    if (!person.SerializeToOstream(&output)) {        cerr << "Failed to write person." << endl;        return -1;    }    output.close();    //从字符串来反序列化    Test::Person person2;    person2.ParseFromString(encode_str);    cout << "person2 is "<<person2.id() << ends << person2.name() << ends << person2.email() << endl;    //从文件流来反序列化    fstream input(file_name, ios::in | ios::binary);    Test::Person person3;    if (!person3.ParseFromIstream(&input)) {        cerr << "Failed to read address book." << endl;        return -1;    }    cout << "person3 is " << person3.id() << ends << person3.name() << ends << person3.email() << endl;     google::protobuf::ShutdownProtobufLibrary();  //关闭protobuf    return 0;}

运行结果为:
这里写图片描述

2. 关闭protobuf

// ===================================================================// Shutdown support.// Shut down the entire protocol buffers library, deleting all static-duration// objects allocated by the library or by generated .pb.cc files.//// There are two reasons you might want to call this:// * You use a draconian definition of "memory leak" in which you expect//   every single malloc() to have a corresponding free(), even for objects//   which live until program exit.// * You are writing a dynamically-loaded library which needs to clean up//   after itself when the library is unloaded.//// It is safe to call this multiple times.  However, it is not safe to use// any other part of the protocol buffers library after// ShutdownProtobufLibrary() has been called.LIBPROTOBUF_EXPORT void ShutdownProtobufLibrary();
0 0