您的位置:首页 > 其它

protobuff反射机制的应用

2018-03-23 12:51 204 查看
//所有的protobuf都继承自Message类, 所以我们可以应用Message类的一些函数完成对不同包的统一解析.
//对于protobuf结构的每一个字段都是一个FieldDescriptor结构, 所以我们可以通过遍历获得每一个字段的信
//息, 例如字段的字段名, 类型, 值等.示例代码如下:

#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/compiler/importer.h>
using namespace google::protobuf;
using namespace google::protobuf::compiler;

int test_func(Message *message) {
if (message == NULL)
{
return false;
}
const Reflection* reflection = message->GetReflection();
if (reflection == NULL)
{
return false;
}
for (int i = 0; i < message->GetDescriptor()->field_count(); i++)
{
const FieldDescriptor* descriptor = message->GetDescriptor()->field(i);
if (descriptor == NULL)
{
return false;
}
switch (descriptor->type())
{
case FieldDescriptor::TYPE_INT32:
reflection->SetInt32(message, descriptor, 1);
int32 val_int32 = reflection->GetInt32(*message, descriptor);
break;
case FieldDescriptor::TYPE_INT64:
reflection->SetInt64(message, descriptor, 1);
int64 val_int64 = reflection->GetInt64(*message, descriptor);
break;
case FieldDescriptor::TYPE_UINT32:
reflection->SetUInt32(message, descriptor, 1);
uint32 val_uint32 = reflection->GetUInt32(*message, descriptor);
break;
case FieldDescriptor::TYPE_UINT64:
reflection->SetUInt64(message, descriptor, 1);
uint64 val_uint64 = reflection->GetUInt64(*message, descriptor);
break;
case FieldDescriptor::TYPE_STRING:
reflection->SetString(message, descriptor, "1");
string val_string = reflection->GetString(*message, descriptor);
break;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: