Skip to content

Instantly share code, notes, and snippets.

@changrui0608
Last active April 24, 2022 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save changrui0608/ac125bcbd162181b62d08b70853b82e0 to your computer and use it in GitHub Desktop.
Save changrui0608/ac125bcbd162181b62d08b70853b82e0 to your computer and use it in GitHub Desktop.
pb to map (c++)
// not tested yet
//
std::multimap<std::string, std::string> MessageToMap(
const google::protobuf::Message& message) {
std::multimap<std::string, std::string> params;
auto* descriptor = message.GetDescriptor();
auto* reflection = message.GetReflection();
int field_count = descriptor->field_count();
for (int i = 0; i < field_count; ++i) {
const google::protobuf::FieldDescriptor* field_descriptor =
descriptor->field(i);
switch (field_descriptor->cpp_type()) {
case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
params.emplace(
field_descriptor->name(),
std::to_string(reflection->GetInt32(message, field_descriptor)));
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
params.emplace(
field_descriptor->name(),
std::to_string(reflection->GetInt64(message, field_descriptor)));
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
params.emplace(
field_descriptor->name(),
std::to_string(reflection->GetUInt32(message, field_descriptor)));
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
params.emplace(
field_descriptor->name(),
std::to_string(reflection->GetUInt64(message, field_descriptor)));
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
params.emplace(
field_descriptor->name(),
std::to_string(reflection->GetFloat(message, field_descriptor)));
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
params.emplace(
field_descriptor->name(),
std::to_string(reflection->GetDouble(message, field_descriptor)));
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
params.emplace(field_descriptor->name(),
reflection->GetEnum(message, field_descriptor)->name());
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
params.emplace(field_descriptor->name(),
reflection->GetString(message, field_descriptor));
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
break; // no-op
}
default:
break;
}
}
return params;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment