前言
protobuf有 proto2 和 proto3 两个主要的并且差异很大的版本,所以在使用protobuf前要明确使用的版本。
序列化成字符串
将 message 结构对象序列化的函数有很多,即使是序列化成字符串也有多个函数可以使用,比如SerializeToString
,SerializePartialToString
、SerializeAsString
、SerializePartialAsString
等等。
SerializeToString和SerializeAsString区别
这两个很好区分的,可以从源码中一眼就分辨出来:
std::string MessageLite::SerializeAsString() const {
// If the compiler implements the (Named) Return Value Optimization,
// the local variable 'output' will not actually reside on the stack
// of this function, but will be overlaid with the object that the
// caller supplied for the return value to be constructed in.
std::string output;
if (!AppendToString(&output)) output.clear();
return output