记录一下
定义person.proto文件,
package tutorial;
message Person {
required int32 id = 1;
optional string name = 2;
optional string email = 3;
}
#include "ProtoImporter.h"
using namespace google::protobuf;
void reflectionFill(Message* message, const FieldDescriptor* descriptor, const Reflection* reflection, std::map<string, string> row)
{
assert(descriptor != NULL);
//current not support for repeated label
if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
return;
}
const char* name = descriptor->name().c_str();
switch (descriptor->type()) {
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_INT64:
reflection->SetInt64(message, descriptor, (long long)row[name].c_str()); break;
case FieldDescriptor::TYPE_UINT64:
reflection->SetInt64(message, descriptor, (unsigned long long)row[name].c_str()); break;
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_INT32:
reflection->SetInt32(message, descriptor, (int)row[name].c_str()); break;
case FieldDescriptor::TYPE_UINT32:
reflection->SetInt32(message, descriptor, (unsigned int)row[name].c_str()); break;
case FieldDescriptor::TYPE_STRING:
reflection->SetString(message, descriptor, (std::string)row[name]); break;
case FieldDescriptor::TYPE_DOUBLE:
reflection->SetDouble(message, descriptor, (double)atof(row[name].c_str())); break;
case FieldDescriptor::TYPE_FLOAT:
reflection->SetFloat(message, descriptor, (float)atof(row[name].c_str())); break;
case FieldDescriptor::TYPE_BOOL:
reflection->SetBool(message, descriptor, (bool)row[name].c_str()); break;
default: std::cerr << "not support type " << descriptor->type() << std::endl;
}
}
void convert(std::map<string, string> rowInfo, std::string& data)
{
google::protobuf::Message* message = sProtoImporter.createDynamicMessage("Person");
//Message* message = createMessage(message_type);
const Reflection* reflection = message->GetReflection();
const Descriptor* descriptor = message->GetDescriptor();
for (int i = 0; i < descriptor->field_count(); ++i)
{
reflectionFill(message, descriptor->field(i), reflection, rowInfo);
}
message->SerializeToString(&data);
delete message;
}
void TestProto()
{
// sql::row rowInfo;
std::map<string, string> rowInfo;
rowInfo["id"] = "20001";
rowInfo["name"] = "testname";
rowInfo["email"] = "aaa@163.com";
std::string data;
if (sProtoImporter.Import("person.proto"))
{
convert(rowInfo, data);
}
printf("get: %s", data.c_str());
return;
}