文章目录
一、补充API说明
1)protobuf mutable_* 函数
- 作用:
若该对象存在,则直接返回该对象,若不存在则新new 一个。
- 使用:
//proto
message Answer
{
optional uint32 choice = 1;
optional uint32 id = 2;
}
message Info
{
required Answer answer = 1
}
message Rsp
{
repeated Info info = 1;
}
//C++
Rsp rsp;
for(int index = 0;index<info.answer_size();index++)
{
Info * info = rsp.add_info();
Answer* ans = info->mutable_answer();
ans->set_choice(index);
ans->set_id(index+1);
}
2)bool ParseFromString(const string& data)和bool SerializeToString(string* output) const
- ParseFromString() 作用
函数是protobuf 提供的一个C++ API,它的功能就是将string 里面的数据反序列化(解析)到指定的消息结构类中。
它其实是一个消息结构类的成员函数,反序列化之后,该消息结构类中的数据成员将会被填充,且有效。
- SerializeToString() 作用
protobuf 提供的一个C++ API,它的功能与parseFromString() 函数相对应,是将消息结构的数据序列化(填充)到output 所指向的string 对象中。在string 对象中以二进制的形式存储。
- 注意点
1)若要ParseFromString() 函数成功执行并返回true 。还需要注意一点就是输入参数的数据构造要正确,不能多一个也不是少一个字节。
将data 的长度resize() 太大,导致了该函数返回false
3)ParseFromArray
- ParseFromArray作用:
将proto结构体反序列成可以解读的结构体
//proto
message TEAM_MEMBER_MARK_INFO
{
required int32 w = 1;
required int32 x = 1;
required int32 y = 1;
required int32 z = 1;
}
message C2G_TEAM_CHANGE_MARK
{
required TEAM_MEMBER_MARK_INFO mark = 1;
optional bool share_mark;
}
//C++
TEAM_MEMBER_MARK stMark;
C2G_TEAM_CHANGE_MARK msg;
int32_t nRetCode = 0;
nRetCode = msg.ParseFromArray(pBuffer,nSize);
LOG_PROCESS_ERROR(nRetCode);
st.Mark.nw = msg.mark().w();
st.Mark.nw = msg.mark().x();
st.Mark.nw = msg.mark().y();
st.Mark.nw = msg.mark().z();
4)set_allocated_*的使用
//proto
message vector3D
{
required float x = 1;
required float y = 2;
required float z = 3;
};
message PlayerPos
{
required uint32 playerID = 1;
required vector3D pos = 2;
}
//C++
//set_allocated_pos的做法
PlayerPos player;vector3D *tmp = new Vector3D;
tmp->x = 1;
tmp->y = 2;
tmp->z = 3;
player.set_allocated_pos(tmp)
//mutable_pos的方法
inline ::vector3D* PlayerPos::mutable_pos()
{
set_has_pos();
if (pos_ == NULL)
pos_ = new ::vector3D;
return pos_;
}
PlayerPos player;
vector3D *tmp = player.mutable_pos();
tmp->x = 1;
tmp->y = 2;
tmp->z = 3;