Protobuf Any

原文

一下案例是C++版本
1,编写.proto文件
base.proto

syntax = "proto3";  //指定proto编译器版本为3  默认是2
import "google/protobuf/any.proto";  //使用Any必须要导入Any.proto

enum Type
{
    FACE = 0;
    PLATE = 1;
}

message Base
{
    Type type = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
  repeated google.protobuf.Any object = 4;

}

message Face
{
    string name = 1;
}

message Plate
{
    string email = 1;
}

2,生成对应的.cc和.h

protoc  --proto_path=./ --cpp_out=./ ./base.proto 

3,在工程中使用
把生成的.cc和.h文件拷贝到工程目录下,并在使用的地方添加头文件代码如下

#include <iostream>

using namespace std;
#include<fstream>

//input .h
#include"base.pb.h"

int main(int argc, char *argv[])
{
    string filename("prototest1.text"); //序列化保存到本地文件
    fstream output(filename,ios::out | ios::trunc| ios::binary);
    Base base;
    base.set_type(Type::FACE);
    base.set_page_number(2);
    base.set_result_per_page(66);
    Face face;
    face.set_name("lvlvlv");
    base.add_object()->PackFrom(face); //为Any对象赋值
    Plate plate;
    plate.set_email("[email protected]");
    base.add_object()->PackFrom(plate);
    base.SerializeToOstream(&output);//序列化到本地文件
    output.close();
    cout << "Hello World!" << endl;

    string filename2("prototest1.text");
    fstream input(filename2,ios::in |ios::binary);
    Base base2;
    base2.ParseFromIstream(&input); //从本地文件中反序列化过来
    input.close();
    cout<<base2.page_number()<<"  "<<base2.result_per_page()<<endl;

//从Any对象中恢复到具体对象
        for(const ::google::protobuf::Any& object : base2.object()) 
        {
            if(object.Is<Face>()) //判断对象类型
            {
                Face face;
                object.UnpackTo(&face);
                cout<<"name "<<face.name()<<endl;
            }else if(object.Is<Plate>())
            {
                Plate plate;
                object.UnpackTo(&plate);
                cout<<plate.email()<<endl;
            }
        }


    return 0;
}

猜你喜欢

转载自blog.csdn.net/CAir2/article/details/79169022