• 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;
    }
    
  • 相关阅读:
    net core 上传并使用EPPlus导入Excel文件
    mysql 动态行转列
    Net Core2.0 升级到.Net Core 2.1
    把旧系统迁移到.Net Core 2.0 日记 (13) --图形验证码
    把旧系统迁移到.Net Core 2.0 日记 (12) --发布遇到的问题
    TCP传输协议
    css命名规范: BEM 的命名法
    http与https
    网络通信原理和过程
    PWA,SPA,MPA
  • 原文地址:https://www.cnblogs.com/silvermagic/p/9087617.html
Copyright © 2020-2023  润新知