C++ protobuf相关理解

官网:https://protobuf.dev/reference/cpp/api-docs/

protobuf操作

protobuf中,repeated字段进行删除字段:
Protobuf v2
可以使用SwapElements(int index1, int index2),将要删除的字段移到最后,再用RemoveLast(),删除最后的元素。
Protobuf v3更新
可以通过iterator RepeatedField::erase(const_iterator position)可以在任意位置删除
 
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++ 中,序列化使用 SerializeToArraySerializeToString 方法,而反序列化则使用 ParseFromArrayParseFromString 方法。这些方法能够有效地将 Protocol Buffers 的消息对象和二进制数据之间进行转换,实现数据的有效交换和存储。

 

 

posted @ 2023-12-07 00:22  CodeRabbit_joion  阅读(568)  评论(0)    收藏  举报