码迷,mamicode.com
首页 > 其他好文 > 详细

ProtoBuf练习(四)

时间:2018-05-25 13:46:49      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:bre   argv   fstream   start   UNC   ali   目录结构   union   turn   

其中一个类型

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;
}

ProtoBuf练习(四)

标签:bre   argv   fstream   start   UNC   ali   目录结构   union   turn   

原文地址:https://www.cnblogs.com/silvermagic/p/9087617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!