假设,你的 protobuf message 看起来像这样:
message Object
{
... = 1;
... = 2;
... = 3;
}
然后在同一个文件中再引入 1 个message,这是这些Objects 的集合。
message Objects
{
repeated Object array = 1;
}
因此,当您有许多元素时,您可以简单地使用Objects 并在Objects 本身上使用SerializeAsString()。这将节省您单独序列化单个Object 并放置您自己的手工分隔符的工作。您可以使用Objects 的单个实例序列化所有Objects。
使用这种方法,您将所有解析和序列化工作也委托给 Protobuf 库。我在我的项目中使用它,它就像一个魅力。
此外,明智地使用Objects 还可以避免额外复制Object。您可以向其中添加项目并使用索引进行访问。 protobufs 的 repeated 字段符合 C++11,因此您也可以将其与迭代器或增强的 for 循环一起使用。
需要注意的是,当您将Objects::SerializeAsString() 的输出存储到文件中时,您应该首先输入string 的长度,然后输入实际的序列化字符串。读取时,您可以先读取长度,然后再读取总字节数。为了方便使用,我扩展了std::fstream并重载了以下方法:
struct fstreamEncoded : std::fstream
{
// other methods
void // returns `void` to avoid multiple `<<` in a single line
operator<< (const string& content)
{ // below casting would avoid recursive calling of this method
// adding `length() + 1` to include the protobuf's last character as well
static_cast<std::fstream&>(*this) << (content.length() + 1) << "\n" << content << std::endl;
}
string
getline ()
{
char length_[20] = {};
std::istream::getline(length_, sizeof(length_) - 1);
if(*length_ == 0)
return "";
const size_t length = std::atol(length_); // length of encoded input
string content(length, 0); // resize the `string`
read(&content[0], length); // member of `class istream`
return content;
}
}
以上只是一个插图。您可以根据自己的项目需求进行跟进。