proto3 any 的操作
作者:互联网
person.proto
syntax = "proto3";
import "google/protobuf/any.proto";
message Apply_data
{
uint32 apply_data_id = 1;
uint64 apply_time = 2;
}
message Apply_list
{
uint32 apply_list_id = 1;
}
message Test
{
int32 id = 1;
google.protobuf.Any data = 2;
}
main.cpp
#include <iostream>
#include "person.pb.h"
#include "MsgHead.h"
#include <google/protobuf/any.h>
#include <google/protobuf/any.pb.h>
using namespace std;
typedef google::protobuf::Message GPMessage;
typedef google::protobuf::Any Any;
void checkAny(const Test& test) {
if (!test.has_data()) {
cout << "not has_data" << endl;
return ;
}
Apply_data data1;
Apply_list list1;
//判断是否是和发的proto any
//if (!test.mutable_data()->UnpackTo(&data1)) {
if (test.data().Is<Apply_data>()) {
//解析
if (test.data().UnpackTo(&data1)) {
cout << data1.apply_data_id() << endl;
cout << "unpackTo data success" << endl;
} else {
cout << "unpackTo data error" << endl;
}
} else {
cout << "is not apply_data" << endl;
}
if (test.data().Is<Apply_list>()) {
//解析
if (test.data().UnpackTo(&list1)) {
cout << list1.apply_list_id() << endl;
cout << "unpackTo list success" << endl;
} else {
cout << "unpackTo list error" << endl;;
}
} else {
cout << "is not apply_list" << endl;
}
}
int main() {
Test test;
Apply_data data;
data.set_apply_data_id(111);
Apply_list list;
list.set_apply_list_id(222);
//设置any数据
cout << "set apply_data data:" << endl;
test.mutable_data()->PackFrom(data);
//找到any数据 解析
checkAny(test);
//----------------------
//设置any数据
cout << "set apply_list data:" << endl;
test.mutable_data()->PackFrom(list);
//找到any数据 解析
checkAny(test);
//----------------------
//清空
cout << "clear data:" << endl;
test.clear_data();
checkAny(test);
return 0;
}
make:
protoc --cpp_out=./ *.proto
g++ -o main main.cpp person.pb.cc -lprotobuf -std=c++11 -g -lpthread
参考:
https://blog.csdn.net/u011573853/article/details/73060934
https://developers.google.com/protocol-buffers/docs/proto3#any
标签:google,cout,proto3,test,操作,include,data,any 来源: https://blog.csdn.net/u012662731/article/details/88077828