如何在 protobuf 中使用反射将预分配的消息设置为字段C++

How to set a preallocated message as field using reflection in protobuf on C++?

本文关键字:消息 预分配 设置 C++ 字段 反射 protobuf      更新时间:2023-10-16

我有这样的代码:

TestMessage* output;
::google::protobuf::Message* input;
// ...
auto extension_field = input->GetDescriptor()->extension(i);
// ...
auto reflection = output->GetReflection();
reflection->MutableMessage(output, extension_field)->CopyFrom(*input);

此代码接受两条消息,检查一条是另一条的扩展,将输入消息复制到输出消息的相应扩展字段。

我想优化它 - 并将复制替换为"移动"。如何使用reflection

您可以得到的最接近的方法是使用 Reflection::Swap 代替 CopyFrom 。 顶级对象不会被使用,但其所有子对象(字符串、子消息等)将被使用。

auto msg = reflection->MutableMessage(output, output_field);
msg->GetReflection()->Swap(msg, input);
delete input;