protobuf根据字段名修改值

int CardMgr::getValue(int nCardId, string strParam)
{
	PlayerDbMsg::CardBean* pCardBean = getCard(nCardId);
	if(NULL == pCardBean)
		return 0;
	const google::protobuf::Descriptor* des = pCardBean->GetDescriptor();
	const google::protobuf::FieldDescriptor* fdes = des->FindFieldByName(strParam);
	if(NULL == fdes)
		return 0;
	if(fdes->type()!= google::protobuf::FieldDescriptor::TYPE_INT32)
		return 0;
	const google::protobuf::Reflection* pReflection = pCardBean->GetReflection();
	return pReflection->GetInt32(*pCardBean, fdes);
}

bool CardMgr::setValue(int nCardId, string strParam, int nValue)
{
	PlayerDbMsg::CardBean* pCardBean = getCard(nCardId);
	if(NULL == pCardBean)
		return false;
	const google::protobuf::Descriptor* des = pCardBean->GetDescriptor();
	const google::protobuf::FieldDescriptor* fdes = des->FindFieldByName(strParam);
	if(NULL == fdes)
		return false;
	if(fdes->type()!= google::protobuf::FieldDescriptor::TYPE_INT32)
		return false;
	const google::protobuf::Reflection* pReflection = pCardBean->GetReflection();
	pReflection->SetInt32(pCardBean, fdes, nValue);
	return true;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C语言中使用Protobuf,你需要进行以下几个步骤: 1. 首先,你需要下载并安装Protobuf编译器,它将用于将.proto文件编译成可用于C语言的源代码文件。你可以从Google的Protobuf GitHub页面下载编译器。 2. 编写一个.proto文件,描述你的消息结构和字段。在.proto文件中,你可以定义消息的名称、字段的类型和名称等。请确保.proto文件与你的C代码在同一个目录下。 3. 使用Protobuf编译器将.proto文件编译成C语言源代码。在命令行中,导航到.proto文件所在的目录,并运行以下命令: ``` protoc --proto_path=. --c_out=. your_proto_file.proto ``` 其中,`your_proto_file.proto`是你的.proto文件的名称。 这将生成一个或多个包含消息定义和序列化/反序列化方法的文件,通常是以`.pb-c.h`和`.pb-c.c`为后缀的文件。 4. 在你的C代码中包含生成的头文件`.pb-c.h`,并使用生成的函数来处理你的消息。 你可以使用`protobuf-c`库中提供的函数来进行消息的序列化和反序列化。例如,你可以使用`protobuf_c_message_pack()`函数将消息打包成字节流,使用`protobuf_c_message_unpack()`函数从字节流中解包消息。 此外,你还可以使用生成的`.pb-c.h`文件中的其他函数,如`your_message_init()`、`your_message_get_字段名()`和`your_message_set_字段名()`来初始化、获取和设置消息的字段。 注意,你需要在编译时链接`protobuf-c`库,以便使用Protobuf相关函数。 这段代码可以帮助你更好地理解在C语言中使用Protobuf的过程。它展示了如何创建一个消息、设置字段、将消息序列化为字节流,并将字节流反序列化为消息: ```c #include "person.pb-c.h" int main() { // 创建一个Person消息 Person person = PERSON__INIT; // 设置字段 person.name = "John"; person.email = "john@example.com"; person.id = 123; // 将消息序列化为字节流 size_t packed_size = person__get_packed_size(&person); uint8_t *buffer = malloc(packed_size); person__pack(&person, buffer); // 将字节流反序列化为消息 Person *unpacked_person = person__unpack(NULL, packed_size, buffer); // 打印字段 printf("Name: %s\n", unpacked_person->name); printf("Email: %s\n", unpacked_person->email); printf("ID: %d\n", unpacked_person->id); // 释放内存 person__free_unpacked(unpacked_person, NULL); free(buffer); return 0; } ``` 此示例演示了如何使用Protobuf在C语言中创建、设置、序列化和反序列化消息。你可以根据自己的需求修改此示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值