---
title: "protobuf 反射"
author: "tcspecial"
date: "2019-02-02T19:58:18Z"
tags: []
categories: ["开源软件"]
slug: "protobuf"
draft: false
lastmod: "2019-06-14T15:41:30Z"
id: 2437355
url: "https://tcspecial.iteye.com/blog/2437355"
---

protobuf 提供了反射API，可以很方便操作pb字段。

```
// 遍历pb字段
bool ParsePb(google::protobuf::Message *oReq, std::map<std::string, std::string> &vParams)
{
    // Descriptor: message类型定义描述
    const google::protobuf::Descriptor *descriptor = oReq->GetDescriptor();
    // Reflection: 动态读写pb字段
    const google::protobuf::Reflection *reflection = oReq->GetReflection();

    google::protobuf::FieldDescriptor *field = NULL;
    int count = descriptor->field_count();

    string sKey;
    string sVal;
    for (int i=0; i<count; i++)
    {
    	// 字段
        field = descriptor->field(i);
        sKey = field->name();

        switch (field->cpp_type())
        {
        case FieldDescriptor::CPPTYPE_BOOL:
            sVal = to_string( reflection->GetBool(*oReq, field) );
            break;
        case FieldDescriptor::CPPTYPE_INT32:
            sVal = to_string( reflection->GetInt32(*oReq, field) );
            break;
        case FieldDescriptor::CPPTYPE_UINT32:
            sVal = to_string( reflection->GetUInt32(*oReq, field) );
            break;
        case FieldDescriptor::CPPTYPE_INT64:
            sVal = to_string( reflection->GetInt64(*oReq, field) );
            break;
        case FieldDescriptor::CPPTYPE_UINT64:
            sVal = to_string( reflection->GetUInt64(*oReq, field) );
            break;
        case FieldDescriptor::CPPTYPE_FLOAT:
            sVal = to_string( reflection->GetFloat(*oReq, field) );
            break;
        case FieldDescriptor::CPPTYPE_DOUBLE:
            sVal = to_string( reflection->GetDouble(*oReq, field) );
            break;
        case FieldDescriptor::CPPTYPE_STRING:
            sVal = reflection->GetString(*oReq, field);
            break;
        default:
        	sVal = "";
            break;
        }

        vParams.insert({sKey, sVal});
    }

    return true;
}
```

 

开源库[pb2json](https://github.com/shafreeck/pb2json)（实现pb与json互转）也是基于反射实现。