protobuf any 的操作c++

it2023-07-20  74

https://blog.csdn.net/u012662731/article/details/88077828

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

运行结果:

set apply_data data: 111 unpackTo data success is not apply_list set apply_list data: is not apply_data 222 unpackTo list success clear data: not has_data

个人感觉有点像模版,下一篇介绍any源码的实现,看本质是不是模板。

最新回复(0)