ProtoBuf练习(四)

其中一个类型

protobuf语言的oneof字段类型相当于C++语言的联合数据类型

工程目录结构

$ ls proto/
sample_oneof.proto

proto文件

$ cat proto/sample_oneof.proto
syntax = "proto3";

message sample_oneof
{
    oneof oneof_name
    {
        int32 foo_int = 1;
        string foo_string = 2;
    }
}

读写源文件

$ cat reader.cpp
#include <fstream>
#include <iostream>
#include "sample_oneof.pb.h"

using namespace std;

int main(int argc, char *argv[])
{
    fstream input("./log", ios::in | ios::binary);
    cout << "Deserialize start." << endl;

    sample_oneof s;
    if (!s.ParseFromIstream(&input))
    {
        cout << "Deserialize failed." << endl;
        return -1;
    }

    switch (s.oneof_name_case())
    {
        case sample_oneof::OneofNameCase::kFooInt:
            cout << "Int:" << s.foo_int() << endl;
            break;
        case sample_oneof::OneofNameCase::kFooString:
            cout << "String:" << s.foo_string() << endl;
            break;
        default:
            cout << "ONEOF_NAME_NOT_SET" << endl;
            break;
    }

    cout << "Deserialize end." << endl;
    input.close();
    return 0;
}

$ cat writer.cpp
#include <fstream>
#include <iostream>
#include "sample_oneof.pb.h"

using namespace std;

int main(int argc, char *argv[])
{
    sample_oneof s;
    s.set_foo_string("sample union");

    fstream output("./log", ios::out | ios::trunc | ios::binary); 
    cout << "Serialize start." << endl;
    if (!s.SerializeToOstream(&output))
        {
                cout << "Serialize failed." << endl;
                return -1;
        }
    output.close();
    cout << "Serialize end." << endl;
    return 0;
}
posted @ 2018-05-25 11:22  银魔术师  阅读(783)  评论(0编辑  收藏  举报