C++ protobuf相关理解
官网:https://protobuf.dev/reference/cpp/api-docs/
protobuf操作
protobuf中,repeated字段进行删除字段:
Protobuf v2
可以使用SwapElements(int index1, int index2),将要删除的字段移到最后,再用RemoveLast(),删除最后的元素。
Protobuf v3更新
message GuiChild
{
optional string widgetName = 1;
//..
}
message GuiLayout
{
repeated ChildGuiElement children = 1;
//..
}
typedef google_public::protobuf::RepeatedPtrField<GuiChild> RepeatedField;
typedef google_public::protobuf::Message Msg;
GuiLayout guiLayout;
//Init children as necessary..
GuiChild child;
//Set child fileds..
DeleteElementsFromRepeatedField(*child, guiLayout->mutable_children());
void DeleteElementsFromRepeatedField(const Msg& msg, RepeatedField* repeatedField)
{
for (RepeatedField::iterator it = repeatedField->begin(); it != repeatedField->end(); it++)
{
if (google_public::protobuf::util::MessageDifferencer::Equals(*it, msg))
{
repeatedField->erase(it);
break;
}
}
}
序列化与反序列化
在 C++ 中,序列化使用
SerializeToArray 或 SerializeToString 方法,而反序列化则使用 ParseFromArray 或 ParseFromString 方法。这些方法能够有效地将 Protocol Buffers 的消息对象和二进制数据之间进行转换,实现数据的有效交换和存储。

浙公网安备 33010602011771号