版本3.13.0
因为google/protobuf/any.proto,不带option optimize_for = LITE_RUNTIME;且没有编译到lite版中,所以我们自己实现一个any
syntax = "proto3";
option optimize_for = LITE_RUNTIME;
message VdiAny {
string type_url = 1;
bytes value = 2;
}
原样拷贝过来加上option optimize_for = LITE_RUNTIME;
生成对应的message类,在生成的类中加上packFrom和unPackTo
template <typename T, class = typename std::enable_if<std::is_convertible<T, const ::PROTOBUF_NAMESPACE_ID::MessageLite&>::value>::type>
void PackFrom(const T& message) {
_any_metadata_.PackFrom<T>(message);
}
template <typename T, class = typename std::enable_if<std::is_convertible<T, const ::PROTOBUF_NAMESPACE_ID::MessageLite&>::value>::type>
void PackFrom(const T& message,
const std::string& type_url_prefix) {
_any_metadata_.PackFrom<T>(message, type_url_prefix);
}
template <typename T, class = typename std::enable_if<std::is_convertible<T, const ::PROTOBUF_NAMESPACE_ID::MessageLite&>::value>::type>
bool UnpackTo(T* message) const {
return _any_metadata_.UnpackTo<T>(message);
}
//添加一个成员变量
::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata _any_metadata_;
//构造函数中添加成员变量的初始化
VdiAny::VdiAny(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(arena) ,
_any_metadata_(&type_url_, &value_) { //调用成员变量的构造函数
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:VdiAny)
}
demo
syntax = "proto3";
//import "google/protobuf/any.proto";
import "vdiAny.proto";
option optimize_for = LITE_RUNTIME;
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;
VdiAny data = 2;
}
Test test;
Apply_data data;
data.set_apply_data_id(111);
Apply_list list;
list.set_apply_list_id(222);
//设置any数据
ZTSLOG(INFO, "set apply_data data:");
test.mutable_data()->PackFrom(data);
if (test.data().Is<Apply_data>()) {
//解析
if (test.data().UnpackTo(&data1)) {
ZTSLOG(INFO, data1.apply_data_id());
ZTSLOG(INFO, "unpackTo data success");
}
else {
ZTSLOG(INFO, "unpackTo data error");
}
}
else {
ZTSLOG(INFO, "is not apply_data");
}