ProtoBuf练习

Posted 银魔术师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

以上是关于ProtoBuf练习的主要内容,如果未能解决你的问题,请参考以下文章

ProtoBuf练习

ProtoBuf练习

ProtoBuf练习

ProtoBuf练习

ProtoBuf练习

spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段