ProtoBuf練習(四)
阿新 • • 發佈:2018-05-25
sage spa default syn break ase [] fault parse
其中一個類型
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練習(四)