protobuf -序列化

本文介绍了protobuf的序列化方法,包括SerializeToString和SerializeAsString的区别,主要在于参数和返回值类型的不同。同时,文章详细探讨了SerializeToString与SerializePartialToString的区别,后者在Debug模式下会进行required字段的初始化检查,而在Release模式下则无此检查,允许未初始化的message进行序列化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

protobuf有 proto2 和 proto3 两个主要的并且差异很大的版本,所以在使用protobuf前要明确使用的版本。

序列化成字符串

将 message 结构对象序列化的函数有很多,即使是序列化成字符串也有多个函数可以使用,比如SerializeToStringSerializePartialToStringSerializeAsStringSerializePartialAsString 等等。

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值