DB2Proto

记录一下

定义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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值