[Protobuf] 快速上手:安全高效的序列化指南

[复制链接]
发表于 2025-7-19 17:03:59 | 显示全部楼层 |阅读模式
标题:[Protobuf] (1)快速上手
@水墨不写bug






一、什么是protobuf?

Protocol Buffers(简称 protobuf)是由 Google 开发的一种与语言无关、平台无关、可扩展序列化数据结构的方法。它用于结构化数据的序列化与反序列化,类似于 XMLJSON,但更小、更快、更简单

二、protobuf的特点

protobuf 可以把数据结构(比如对象或消息)编码成紧凑的二进制格式,之后再还原回原始的数据结构。 这阐明protobuf编码是比较安全的,由于二进制无法被直接阅读。
其他重要特点:


  • 跨语言(支持 Java、C++、Python、Go、C#、JavaScript 等多种语言)
  • 二进制格式,高效且体积小
  • 向后兼容和向前兼容性好(得当长期演进的体系)
  • 需要提前定义数据结构(.proto 文件)
减少开发周期和负担
protobuf可以通过protoc编译器来编译proto文件来生成对应的头文件和源文件,内部已经实现了序列化和反序列化的接口。- - - 节省开发时间,制止重复性造轮子

三、使用protobuf的过程?

1、定义消息格式(.proto文件)

(1)指定语法版本

创建**.proto**文件后,首行需要先指定protobuf的语法版本,假如不指定,默认使用proto2。一般我们都使用proto3。 - - - proto3的语法更加简便,支持更多的语言(比如C#)
(2)package 声明符

在proto文件编译之后,假如写了pageage声明,那么cc和h文件内部会被定名空间封装。
假如没有package声明,则cc和h文件的对应类不会被定名空间包裹。
2、使用protoc编译器生成代码

经过1、2两步,后,就可以编写消息的内部数据结构了,假如如下设计(文件名称为 “contact.proto” ):
  1. //首行:语法指定行
  2. syntax = "proto3";
  3. //package 声明符
  4. package contast;
  5. //定义联系人信息
  6. message PersonInfo
  7. {
  8.     string name = 1;
  9.     int32 age = 2;
  10. }
复制代码
下一步就需要编译:
(1)当前目录直接编译:

  1. protoc --cpp_out=. contact.proto
复制代码
这段指令的含义如下:


  • protoc:表示 Protocol Buffers 的编译器程序(Protocol Compiler)。
  • --cpp_out=.:指定生成 C++ 语言的代码文件,并将生成的文件输出到当前目录(. 代表当前目录)。
  • contact.proto:需要被编译的 proto 文件,即你定义了消息结构的协议文件。
综合解释
这条命令的作用是:
使用 Protocol Buffers 的编译器 protoc,将 contact.proto 文件中定义的消息结构,自动生成对应的 C++ 源代码文件(通常为 contact.pb.h 和 contact.pb.cc),并把它们输出到当前目录下。
如许你就可以在 C++ 项目中直接包含和使用这些自动生成的代码了。
(2)指定目录编译

这种情况适用于当前没有处在contact.proto文件所在的目录时:
  1. protoc -I contact_dir/ --cpp_out=contact_dir/ contact.proto
复制代码
这段指令的含义如下:


  • protoc
    Protocol Buffers 的编译器(protocol compiler)。
  • -I contact_dir/
    指定包含 proto 文件的搜索目录(即 import 路径)。表示编译器在 contact_dir/ 目录下查找 proto 文件及其 import 的依赖。
  • --cpp_out=contact_dir/
    指定输出目录为 contact_dir/,并生成 C++ 源代码(通常为 .pb.h 和 .pb.cc 文件)。
  • contact.proto
    要编译的 proto 文件,定义了详细的数据结构。

综合解释:
这条命令会让 protoc 在 contact_dir/ 目录下查找 contact.proto,将其编译为 C++ 源代码,并把生成的 .pb.h 和 .pb.cc 文件输出到同样的 contact_dir/ 目录下。
这种写法常用于项目结构较复杂时,便于管理 proto 文件及生成的代码。

3、在业务中引入并使用生成的类

通过protoc编译proto文件之后,会生成下面两个文件:
  1. // Generated by the protocol buffer compiler.  DO NOT EDIT!
  2. // NO CHECKED-IN PROTOBUF GENCODE
  3. // source: contact.proto
  4. // Protobuf C++ Version: 6.31.0
  5. #include "contact.pb.h"
  6. #include <algorithm>
  7. #include <type_traits>
  8. #include "google/protobuf/io/coded_stream.h"
  9. #include "google/protobuf/generated_message_tctable_impl.h"
  10. #include "google/protobuf/extension_set.h"
  11. #include "google/protobuf/generated_message_util.h"
  12. #include "google/protobuf/wire_format_lite.h"
  13. #include "google/protobuf/descriptor.h"
  14. #include "google/protobuf/generated_message_reflection.h"
  15. #include "google/protobuf/reflection_ops.h"
  16. #include "google/protobuf/wire_format.h"
  17. // @@protoc_insertion_point(includes)
  18. // Must be included last.
  19. #include "google/protobuf/port_def.inc"
  20. PROTOBUF_PRAGMA_INIT_SEG
  21. namespace _pb = ::google::protobuf;
  22. namespace _pbi = ::google::protobuf::internal;
  23. namespace _fl = ::google::protobuf::internal::field_layout;
  24. namespace contact {
  25. inline constexpr Info::Impl_::Impl_(
  26.     ::_pbi::ConstantInitialized) noexcept
  27.       : _cached_size_{0},
  28.         name_(
  29.             &::google::protobuf::internal::fixed_address_empty_string,
  30.             ::_pbi::ConstantInitialized()),
  31.         age_{0} {}
  32. template <typename>
  33. PROTOBUF_CONSTEXPR Info::Info(::_pbi::ConstantInitialized)
  34. #if defined(PROTOBUF_CUSTOM_VTABLE)
  35.     : ::google::protobuf::Message(Info_class_data_.base()),
  36. #else   // PROTOBUF_CUSTOM_VTABLE
  37.     : ::google::protobuf::Message(),
  38. #endif  // PROTOBUF_CUSTOM_VTABLE
  39.       _impl_(::_pbi::ConstantInitialized()) {
  40. }
  41. struct InfoDefaultTypeInternal {
  42.   PROTOBUF_CONSTEXPR InfoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {}
  43.   ~InfoDefaultTypeInternal() {}
  44.   union {
  45.     Info _instance;
  46.   };
  47. };
  48. PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT
  49.     PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 InfoDefaultTypeInternal _Info_default_instance_;
  50. }  // namespace contact
  51. static constexpr const ::_pb::EnumDescriptor *PROTOBUF_NONNULL *PROTOBUF_NULLABLE
  52.     file_level_enum_descriptors_contact_2eproto = nullptr;
  53. static constexpr const ::_pb::ServiceDescriptor *PROTOBUF_NONNULL *PROTOBUF_NULLABLE
  54.     file_level_service_descriptors_contact_2eproto = nullptr;
  55. const ::uint32_t
  56.     TableStruct_contact_2eproto::offsets[] ABSL_ATTRIBUTE_SECTION_VARIABLE(
  57.         protodesc_cold) = {
  58.         0x081, // bitmap
  59.         PROTOBUF_FIELD_OFFSET(::contact::Info, _impl_._has_bits_),
  60.         5, // hasbit index offset
  61.         PROTOBUF_FIELD_OFFSET(::contact::Info, _impl_.name_),
  62.         PROTOBUF_FIELD_OFFSET(::contact::Info, _impl_.age_),
  63.         0,
  64.         1,
  65. };
  66. static const ::_pbi::MigrationSchema
  67.     schemas[] ABSL_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
  68.         {0, sizeof(::contact::Info)},
  69. };
  70. static const ::_pb::Message* PROTOBUF_NONNULL const file_default_instances[] = {
  71.     &::contact::_Info_default_instance_._instance,
  72. };
  73. const char descriptor_table_protodef_contact_2eproto[] ABSL_ATTRIBUTE_SECTION_VARIABLE(
  74.     protodesc_cold) = {
  75.     "\n\rcontact.proto\022\007contact"!\n\004Info\022\014\n\004name"
  76.     "\030\001 \001(\t\022\013\n\003age\030\002 \001(\005b\006proto3"
  77. };
  78. static ::absl::once_flag descriptor_table_contact_2eproto_once;
  79. PROTOBUF_CONSTINIT const ::_pbi::DescriptorTable descriptor_table_contact_2eproto = {
  80.     false,
  81.     false,
  82.     67,
  83.     descriptor_table_protodef_contact_2eproto,
  84.     "contact.proto",
  85.     &descriptor_table_contact_2eproto_once,
  86.     nullptr,
  87.     0,
  88.     1,
  89.     schemas,
  90.     file_default_instances,
  91.     TableStruct_contact_2eproto::offsets,
  92.     file_level_enum_descriptors_contact_2eproto,
  93.     file_level_service_descriptors_contact_2eproto,
  94. };
  95. namespace contact {
  96. // ===================================================================
  97. class Info::_Internal {
  98. public:
  99.   using HasBits =
  100.       decltype(::std::declval<Info>()._impl_._has_bits_);
  101.   static constexpr ::int32_t kHasBitsOffset =
  102.       8 * PROTOBUF_FIELD_OFFSET(Info, _impl_._has_bits_);
  103. };
  104. Info::Info(::google::protobuf::Arena* PROTOBUF_NULLABLE arena)
  105. #if defined(PROTOBUF_CUSTOM_VTABLE)
  106.     : ::google::protobuf::Message(arena, Info_class_data_.base()) {
  107. #else   // PROTOBUF_CUSTOM_VTABLE
  108.     : ::google::protobuf::Message(arena) {
  109. #endif  // PROTOBUF_CUSTOM_VTABLE
  110.   SharedCtor(arena);
  111.   // @@protoc_insertion_point(arena_constructor:contact.Info)
  112. }
  113. PROTOBUF_NDEBUG_INLINE Info::Impl_::Impl_(
  114.     ::google::protobuf::internal::InternalVisibility visibility,
  115.     ::google::protobuf::Arena* PROTOBUF_NULLABLE arena, const Impl_& from,
  116.     const ::contact::Info& from_msg)
  117.       : _has_bits_{from._has_bits_},
  118.         _cached_size_{0},
  119.         name_(arena, from.name_) {}
  120. Info::Info(
  121.     ::google::protobuf::Arena* PROTOBUF_NULLABLE arena,
  122.     const Info& from)
  123. #if defined(PROTOBUF_CUSTOM_VTABLE)
  124.     : ::google::protobuf::Message(arena, Info_class_data_.base()) {
  125. #else   // PROTOBUF_CUSTOM_VTABLE
  126.     : ::google::protobuf::Message(arena) {
  127. #endif  // PROTOBUF_CUSTOM_VTABLE
  128.   Info* const _this = this;
  129.   (void)_this;
  130.   _internal_metadata_.MergeFrom<::google::protobuf::UnknownFieldSet>(
  131.       from._internal_metadata_);
  132.   new (&_impl_) Impl_(internal_visibility(), arena, from._impl_, from);
  133.   _impl_.age_ = from._impl_.age_;
  134.   // @@protoc_insertion_point(copy_constructor:contact.Info)
  135. }
  136. PROTOBUF_NDEBUG_INLINE Info::Impl_::Impl_(
  137.     ::google::protobuf::internal::InternalVisibility visibility,
  138.     ::google::protobuf::Arena* PROTOBUF_NULLABLE arena)
  139.       : _cached_size_{0},
  140.         name_(arena) {}
  141. inline void Info::SharedCtor(::_pb::Arena* PROTOBUF_NULLABLE arena) {
  142.   new (&_impl_) Impl_(internal_visibility(), arena);
  143.   _impl_.age_ = {};
  144. }
  145. Info::~Info() {
  146.   // @@protoc_insertion_point(destructor:contact.Info)
  147.   SharedDtor(*this);
  148. }
  149. inline void Info::SharedDtor(MessageLite& self) {
  150.   Info& this_ = static_cast<Info&>(self);
  151.   this_._internal_metadata_.Delete<::google::protobuf::UnknownFieldSet>();
  152.   ABSL_DCHECK(this_.GetArena() == nullptr);
  153.   this_._impl_.name_.Destroy();
  154.   this_._impl_.~Impl_();
  155. }
  156. inline void* PROTOBUF_NONNULL Info::PlacementNew_(
  157.     const void* PROTOBUF_NONNULL, void* PROTOBUF_NONNULL mem,
  158.     ::google::protobuf::Arena* PROTOBUF_NULLABLE arena) {
  159.   return ::new (mem) Info(arena);
  160. }
  161. constexpr auto Info::InternalNewImpl_() {
  162.   return ::google::protobuf::internal::MessageCreator::CopyInit(sizeof(Info),
  163.                                             alignof(Info));
  164. }
  165. constexpr auto Info::InternalGenerateClassData_() {
  166.   return ::google::protobuf::internal::ClassDataFull{
  167.       ::google::protobuf::internal::ClassData{
  168.           &_Info_default_instance_._instance,
  169.           &_table_.header,
  170.           nullptr,  // OnDemandRegisterArenaDtor
  171.           nullptr,  // IsInitialized
  172.           &Info::MergeImpl,
  173.           ::google::protobuf::Message::GetNewImpl<Info>(),
  174. #if defined(PROTOBUF_CUSTOM_VTABLE)
  175.           &Info::SharedDtor,
  176.           ::google::protobuf::Message::GetClearImpl<Info>(), &Info::ByteSizeLong,
  177.               &Info::_InternalSerialize,
  178. #endif  // PROTOBUF_CUSTOM_VTABLE
  179.           PROTOBUF_FIELD_OFFSET(Info, _impl_._cached_size_),
  180.           false,
  181.       },
  182.       &Info::kDescriptorMethods,
  183.       &descriptor_table_contact_2eproto,
  184.       nullptr,  // tracker
  185.   };
  186. }
  187. PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 const
  188.     ::google::protobuf::internal::ClassDataFull Info_class_data_ =
  189.         Info::InternalGenerateClassData_();
  190. PROTOBUF_ATTRIBUTE_WEAK const ::google::protobuf::internal::ClassData* PROTOBUF_NONNULL
  191. Info::GetClassData() const {
  192.   ::google::protobuf::internal::PrefetchToLocalCache(&Info_class_data_);
  193.   ::google::protobuf::internal::PrefetchToLocalCache(Info_class_data_.tc_table);
  194.   return Info_class_data_.base();
  195. }
  196. PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1
  197. const ::_pbi::TcParseTable<1, 2, 0, 25, 2>
  198. Info::_table_ = {
  199.   {
  200.     PROTOBUF_FIELD_OFFSET(Info, _impl_._has_bits_),
  201.     0, // no _extensions_
  202.     2, 8,  // max_field_number, fast_idx_mask
  203.     offsetof(decltype(_table_), field_lookup_table),
  204.     4294967292,  // skipmap
  205.     offsetof(decltype(_table_), field_entries),
  206.     2,  // num_field_entries
  207.     0,  // num_aux_entries
  208.     offsetof(decltype(_table_), field_names),  // no aux_entries
  209.     Info_class_data_.base(),
  210.     nullptr,  // post_loop_handler
  211.     ::_pbi::TcParser::GenericFallback,  // fallback
  212.     #ifdef PROTOBUF_PREFETCH_PARSE_TABLE
  213.     ::_pbi::TcParser::GetTable<::contact::Info>(),  // to_prefetch
  214.     #endif  // PROTOBUF_PREFETCH_PARSE_TABLE
  215.   }, {{
  216.     // int32 age = 2;
  217.     {::_pbi::TcParser::SingularVarintNoZag1<::uint32_t, offsetof(Info, _impl_.age_), 1>(),
  218.      {16, 1, 0, PROTOBUF_FIELD_OFFSET(Info, _impl_.age_)}},
  219.     // string name = 1;
  220.     {::_pbi::TcParser::FastUS1,
  221.      {10, 0, 0, PROTOBUF_FIELD_OFFSET(Info, _impl_.name_)}},
  222.   }}, {{
  223.     65535, 65535
  224.   }}, {{
  225.     // string name = 1;
  226.     {PROTOBUF_FIELD_OFFSET(Info, _impl_.name_), _Internal::kHasBitsOffset + 0, 0,
  227.     (0 | ::_fl::kFcOptional | ::_fl::kUtf8String | ::_fl::kRepAString)},
  228.     // int32 age = 2;
  229.     {PROTOBUF_FIELD_OFFSET(Info, _impl_.age_), _Internal::kHasBitsOffset + 1, 0,
  230.     (0 | ::_fl::kFcOptional | ::_fl::kInt32)},
  231.   }},
  232.   // no aux_entries
  233.   {{
  234.     "\14\4\0\0\0\0\0\0"
  235.     "contact.Info"
  236.     "name"
  237.   }},
  238. };
  239. PROTOBUF_NOINLINE void Info::Clear() {
  240. // @@protoc_insertion_point(message_clear_start:contact.Info)
  241.   ::google::protobuf::internal::TSanWrite(&_impl_);
  242.   ::uint32_t cached_has_bits = 0;
  243.   // Prevent compiler warnings about cached_has_bits being unused
  244.   (void) cached_has_bits;
  245.   cached_has_bits = _impl_._has_bits_[0];
  246.   if ((cached_has_bits & 0x00000001u) != 0) {
  247.     _impl_.name_.ClearNonDefaultToEmpty();
  248.   }
  249.   _impl_.age_ = 0;
  250.   _impl_._has_bits_.Clear();
  251.   _internal_metadata_.Clear<::google::protobuf::UnknownFieldSet>();
  252. }
  253. #if defined(PROTOBUF_CUSTOM_VTABLE)
  254. ::uint8_t* PROTOBUF_NONNULL Info::_InternalSerialize(
  255.     const ::google::protobuf::MessageLite& base, ::uint8_t* PROTOBUF_NONNULL target,
  256.     ::google::protobuf::io::EpsCopyOutputStream* PROTOBUF_NONNULL stream) {
  257.   const Info& this_ = static_cast<const Info&>(base);
  258. #else   // PROTOBUF_CUSTOM_VTABLE
  259. ::uint8_t* PROTOBUF_NONNULL Info::_InternalSerialize(
  260.     ::uint8_t* PROTOBUF_NONNULL target,
  261.     ::google::protobuf::io::EpsCopyOutputStream* PROTOBUF_NONNULL stream) const {
  262.   const Info& this_ = *this;
  263. #endif  // PROTOBUF_CUSTOM_VTABLE
  264.   // @@protoc_insertion_point(serialize_to_array_start:contact.Info)
  265.   ::uint32_t cached_has_bits = 0;
  266.   (void)cached_has_bits;
  267.   // string name = 1;
  268.   if ((this_._impl_._has_bits_[0] & 0x00000001u) != 0) {
  269.     if (!this_._internal_name().empty()) {
  270.       const ::std::string& _s = this_._internal_name();
  271.       ::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
  272.           _s.data(), static_cast<int>(_s.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "contact.Info.name");
  273.       target = stream->WriteStringMaybeAliased(1, _s, target);
  274.     }
  275.   }
  276.   // int32 age = 2;
  277.   if ((this_._impl_._has_bits_[0] & 0x00000002u) != 0) {
  278.     if (this_._internal_age() != 0) {
  279.       target =
  280.           ::google::protobuf::internal::WireFormatLite::WriteInt32ToArrayWithField<2>(
  281.               stream, this_._internal_age(), target);
  282.     }
  283.   }
  284.   if (ABSL_PREDICT_FALSE(this_._internal_metadata_.have_unknown_fields())) {
  285.     target =
  286.         ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray(
  287.             this_._internal_metadata_.unknown_fields<::google::protobuf::UnknownFieldSet>(::google::protobuf::UnknownFieldSet::default_instance), target, stream);
  288.   }
  289.   // @@protoc_insertion_point(serialize_to_array_end:contact.Info)
  290.   return target;
  291. }
  292. #if defined(PROTOBUF_CUSTOM_VTABLE)
  293. ::size_t Info::ByteSizeLong(const MessageLite& base) {
  294.   const Info& this_ = static_cast<const Info&>(base);
  295. #else   // PROTOBUF_CUSTOM_VTABLE
  296. ::size_t Info::ByteSizeLong() const {
  297.   const Info& this_ = *this;
  298. #endif  // PROTOBUF_CUSTOM_VTABLE
  299.   // @@protoc_insertion_point(message_byte_size_start:contact.Info)
  300.   ::size_t total_size = 0;
  301.   ::uint32_t cached_has_bits = 0;
  302.   // Prevent compiler warnings about cached_has_bits being unused
  303.   (void)cached_has_bits;
  304.   ::_pbi::Prefetch5LinesFrom7Lines(&this_);
  305.   cached_has_bits = this_._impl_._has_bits_[0];
  306.   if ((cached_has_bits & 0x00000003u) != 0) {
  307.     // string name = 1;
  308.     if ((cached_has_bits & 0x00000001u) != 0) {
  309.       if (!this_._internal_name().empty()) {
  310.         total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize(
  311.                                         this_._internal_name());
  312.       }
  313.     }
  314.     // int32 age = 2;
  315.     if ((cached_has_bits & 0x00000002u) != 0) {
  316.       if (this_._internal_age() != 0) {
  317.         total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(
  318.             this_._internal_age());
  319.       }
  320.     }
  321.   }
  322.   return this_.MaybeComputeUnknownFieldsSize(total_size,
  323.                                              &this_._impl_._cached_size_);
  324. }
  325. void Info::MergeImpl(::google::protobuf::MessageLite& to_msg, const ::google::protobuf::MessageLite& from_msg) {
  326.   auto* const _this = static_cast<Info*>(&to_msg);
  327.   auto& from = static_cast<const Info&>(from_msg);
  328.   // @@protoc_insertion_point(class_specific_merge_from_start:contact.Info)
  329.   ABSL_DCHECK_NE(&from, _this);
  330.   ::uint32_t cached_has_bits = 0;
  331.   (void) cached_has_bits;
  332.   cached_has_bits = from._impl_._has_bits_[0];
  333.   if ((cached_has_bits & 0x00000003u) != 0) {
  334.     if ((cached_has_bits & 0x00000001u) != 0) {
  335.       if (!from._internal_name().empty()) {
  336.         _this->_internal_set_name(from._internal_name());
  337.       } else {
  338.         if (_this->_impl_.name_.IsDefault()) {
  339.           _this->_internal_set_name("");
  340.         }
  341.       }
  342.     }
  343.     if ((cached_has_bits & 0x00000002u) != 0) {
  344.       if (from._internal_age() != 0) {
  345.         _this->_impl_.age_ = from._impl_.age_;
  346.       }
  347.     }
  348.   }
  349.   _this->_impl_._has_bits_[0] |= cached_has_bits;
  350.   _this->_internal_metadata_.MergeFrom<::google::protobuf::UnknownFieldSet>(from._internal_metadata_);
  351. }
  352. void Info::CopyFrom(const Info& from) {
  353. // @@protoc_insertion_point(class_specific_copy_from_start:contact.Info)
  354.   if (&from == this) return;
  355.   Clear();
  356.   MergeFrom(from);
  357. }
  358. void Info::InternalSwap(Info* PROTOBUF_RESTRICT PROTOBUF_NONNULL other) {
  359.   using ::std::swap;
  360.   auto* arena = GetArena();
  361.   ABSL_DCHECK_EQ(arena, other->GetArena());
  362.   _internal_metadata_.InternalSwap(&other->_internal_metadata_);
  363.   swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]);
  364.   ::_pbi::ArenaStringPtr::InternalSwap(&_impl_.name_, &other->_impl_.name_, arena);
  365.   swap(_impl_.age_, other->_impl_.age_);
  366. }
  367. ::google::protobuf::Metadata Info::GetMetadata() const {
  368.   return ::google::protobuf::Message::GetMetadataImpl(GetClassData()->full());
  369. }
  370. // @@protoc_insertion_point(namespace_scope)
  371. }  // namespace contact
  372. namespace google {
  373. namespace protobuf {
  374. }  // namespace protobuf
  375. }  // namespace google
  376. // @@protoc_insertion_point(global_scope)
  377. PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::std::false_type
  378.     _static_init2_ [[maybe_unused]] =
  379.         (::_pbi::AddDescriptors(&descriptor_table_contact_2eproto),
  380.          ::std::false_type{});
  381. #include "google/protobuf/port_undef.inc"
复制代码
  1. // Generated by the protocol buffer compiler.  DO NOT EDIT!
  2. // NO CHECKED-IN PROTOBUF GENCODE
  3. // source: contact.proto
  4. // Protobuf C++ Version: 6.31.0
  5. #ifndef contact_2eproto_2epb_2eh
  6. #define contact_2eproto_2epb_2eh
  7. #include <limits>
  8. #include <string>
  9. #include <type_traits>
  10. #include <utility>
  11. #include "google/protobuf/runtime_version.h"
  12. #if PROTOBUF_VERSION != 6031000
  13. #error "Protobuf C++ gencode is built with an incompatible version of"
  14. #error "Protobuf C++ headers/runtime. See"
  15. #error "https://protobuf.dev/support/cross-version-runtime-guarantee/#cpp"
  16. #endif
  17. #include "google/protobuf/io/coded_stream.h"
  18. #include "google/protobuf/arena.h"
  19. #include "google/protobuf/arenastring.h"
  20. #include "google/protobuf/generated_message_tctable_decl.h"
  21. #include "google/protobuf/generated_message_util.h"
  22. #include "google/protobuf/metadata_lite.h"
  23. #include "google/protobuf/generated_message_reflection.h"
  24. #include "google/protobuf/message.h"
  25. #include "google/protobuf/message_lite.h"
  26. #include "google/protobuf/repeated_field.h"  // IWYU pragma: export
  27. #include "google/protobuf/extension_set.h"  // IWYU pragma: export
  28. #include "google/protobuf/unknown_field_set.h"
  29. // @@protoc_insertion_point(includes)
  30. // Must be included last.
  31. #include "google/protobuf/port_def.inc"
  32. #define PROTOBUF_INTERNAL_EXPORT_contact_2eproto
  33. namespace google {
  34. namespace protobuf {
  35. namespace internal {
  36. template <typename T>
  37. ::absl::string_view GetAnyMessageName();
  38. }  // namespace internal
  39. }  // namespace protobuf
  40. }  // namespace google
  41. // Internal implementation detail -- do not use these members.
  42. struct TableStruct_contact_2eproto {
  43.   static const ::uint32_t offsets[];
  44. };
  45. extern "C" {
  46. extern const ::google::protobuf::internal::DescriptorTable descriptor_table_contact_2eproto;
  47. }  // extern "C"
  48. namespace contact {
  49. class Info;
  50. struct InfoDefaultTypeInternal;
  51. extern InfoDefaultTypeInternal _Info_default_instance_;
  52. extern const ::google::protobuf::internal::ClassDataFull Info_class_data_;
  53. }  // namespace contact
  54. namespace google {
  55. namespace protobuf {
  56. }  // namespace protobuf
  57. }  // namespace google
  58. namespace contact {
  59. // ===================================================================
  60. // -------------------------------------------------------------------
  61. class Info final : public ::google::protobuf::Message
  62. /* @@protoc_insertion_point(class_definition:contact.Info) */ {
  63. public:
  64.   inline Info() : Info(nullptr) {}
  65.   ~Info() PROTOBUF_FINAL;
  66. #if defined(PROTOBUF_CUSTOM_VTABLE)
  67.   void operator delete(Info* PROTOBUF_NONNULL msg, std::destroying_delete_t) {
  68.     SharedDtor(*msg);
  69.     ::google::protobuf::internal::SizedDelete(msg, sizeof(Info));
  70.   }
  71. #endif
  72.   template <typename = void>
  73.   explicit PROTOBUF_CONSTEXPR Info(::google::protobuf::internal::ConstantInitialized);
  74.   inline Info(const Info& from) : Info(nullptr, from) {}
  75.   inline Info(Info&& from) noexcept
  76.       : Info(nullptr, ::std::move(from)) {}
  77.   inline Info& operator=(const Info& from) {
  78.     CopyFrom(from);
  79.     return *this;
  80.   }
  81.   inline Info& operator=(Info&& from) noexcept {
  82.     if (this == &from) return *this;
  83.     if (::google::protobuf::internal::CanMoveWithInternalSwap(GetArena(), from.GetArena())) {
  84.       InternalSwap(&from);
  85.     } else {
  86.       CopyFrom(from);
  87.     }
  88.     return *this;
  89.   }
  90.   inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const
  91.       ABSL_ATTRIBUTE_LIFETIME_BOUND {
  92.     return _internal_metadata_.unknown_fields<::google::protobuf::UnknownFieldSet>(::google::protobuf::UnknownFieldSet::default_instance);
  93.   }
  94.   inline ::google::protobuf::UnknownFieldSet* PROTOBUF_NONNULL mutable_unknown_fields()
  95.       ABSL_ATTRIBUTE_LIFETIME_BOUND {
  96.     return _internal_metadata_.mutable_unknown_fields<::google::protobuf::UnknownFieldSet>();
  97.   }
  98.   static const ::google::protobuf::Descriptor* PROTOBUF_NONNULL descriptor() {
  99.     return GetDescriptor();
  100.   }
  101.   static const ::google::protobuf::Descriptor* PROTOBUF_NONNULL GetDescriptor() {
  102.     return default_instance().GetMetadata().descriptor;
  103.   }
  104.   static const ::google::protobuf::Reflection* PROTOBUF_NONNULL GetReflection() {
  105.     return default_instance().GetMetadata().reflection;
  106.   }
  107.   static const Info& default_instance() {
  108.     return *reinterpret_cast<const Info*>(
  109.         &_Info_default_instance_);
  110.   }
  111.   static constexpr int kIndexInFileMessages = 0;
  112.   friend void swap(Info& a, Info& b) { a.Swap(&b); }
  113.   inline void Swap(Info* PROTOBUF_NONNULL other) {
  114.     if (other == this) return;
  115.     if (::google::protobuf::internal::CanUseInternalSwap(GetArena(), other->GetArena())) {
  116.       InternalSwap(other);
  117.     } else {
  118.       ::google::protobuf::internal::GenericSwap(this, other);
  119.     }
  120.   }
  121.   void UnsafeArenaSwap(Info* PROTOBUF_NONNULL other) {
  122.     if (other == this) return;
  123.     ABSL_DCHECK(GetArena() == other->GetArena());
  124.     InternalSwap(other);
  125.   }
  126.   // implements Message ----------------------------------------------
  127.   Info* PROTOBUF_NONNULL New(::google::protobuf::Arena* PROTOBUF_NULLABLE arena = nullptr) const {
  128.     return ::google::protobuf::Message::DefaultConstruct<Info>(arena);
  129.   }
  130.   using ::google::protobuf::Message::CopyFrom;
  131.   void CopyFrom(const Info& from);
  132.   using ::google::protobuf::Message::MergeFrom;
  133.   void MergeFrom(const Info& from) { Info::MergeImpl(*this, from); }
  134.   private:
  135.   static void MergeImpl(::google::protobuf::MessageLite& to_msg,
  136.                         const ::google::protobuf::MessageLite& from_msg);
  137.   public:
  138.   bool IsInitialized() const {
  139.     return true;
  140.   }
  141.   ABSL_ATTRIBUTE_REINITIALIZES void Clear() PROTOBUF_FINAL;
  142.   #if defined(PROTOBUF_CUSTOM_VTABLE)
  143.   private:
  144.   static ::size_t ByteSizeLong(const ::google::protobuf::MessageLite& msg);
  145.   static ::uint8_t* PROTOBUF_NONNULL _InternalSerialize(
  146.       const ::google::protobuf::MessageLite& msg, ::uint8_t* PROTOBUF_NONNULL target,
  147.       ::google::protobuf::io::EpsCopyOutputStream* PROTOBUF_NONNULL stream);
  148.   public:
  149.   ::size_t ByteSizeLong() const { return ByteSizeLong(*this); }
  150.   ::uint8_t* PROTOBUF_NONNULL _InternalSerialize(
  151.       ::uint8_t* PROTOBUF_NONNULL target,
  152.       ::google::protobuf::io::EpsCopyOutputStream* PROTOBUF_NONNULL stream) const {
  153.     return _InternalSerialize(*this, target, stream);
  154.   }
  155.   #else   // PROTOBUF_CUSTOM_VTABLE
  156.   ::size_t ByteSizeLong() const final;
  157.   ::uint8_t* PROTOBUF_NONNULL _InternalSerialize(
  158.       ::uint8_t* PROTOBUF_NONNULL target,
  159.       ::google::protobuf::io::EpsCopyOutputStream* PROTOBUF_NONNULL stream) const final;
  160.   #endif  // PROTOBUF_CUSTOM_VTABLE
  161.   int GetCachedSize() const { return _impl_._cached_size_.Get(); }
  162.   private:
  163.   void SharedCtor(::google::protobuf::Arena* PROTOBUF_NULLABLE arena);
  164.   static void SharedDtor(MessageLite& self);
  165.   void InternalSwap(Info* PROTOBUF_NONNULL other);
  166. private:
  167.   template <typename T>
  168.   friend ::absl::string_view(::google::protobuf::internal::GetAnyMessageName)();
  169.   static ::absl::string_view FullMessageName() { return "contact.Info"; }
  170. protected:
  171.   explicit Info(::google::protobuf::Arena* PROTOBUF_NULLABLE arena);
  172.   Info(::google::protobuf::Arena* PROTOBUF_NULLABLE arena, const Info& from);
  173.   Info(
  174.       ::google::protobuf::Arena* PROTOBUF_NULLABLE arena, Info&& from) noexcept
  175.       : Info(arena) {
  176.     *this = ::std::move(from);
  177.   }
  178.   const ::google::protobuf::internal::ClassData* PROTOBUF_NONNULL GetClassData() const PROTOBUF_FINAL;
  179.   static void* PROTOBUF_NONNULL PlacementNew_(
  180.       const void* PROTOBUF_NONNULL, void* PROTOBUF_NONNULL mem,
  181.       ::google::protobuf::Arena* PROTOBUF_NULLABLE arena);
  182.   static constexpr auto InternalNewImpl_();
  183. public:
  184.   static constexpr auto InternalGenerateClassData_();
  185.   ::google::protobuf::Metadata GetMetadata() const;
  186.   // nested types ----------------------------------------------------
  187.   // accessors -------------------------------------------------------
  188.   enum : int {
  189.     kNameFieldNumber = 1,
  190.     kAgeFieldNumber = 2,
  191.   };
  192.   // string name = 1;
  193.   void clear_name() ;
  194.   const ::std::string& name() const;
  195.   template <typename Arg_ = const ::std::string&, typename... Args_>
  196.   void set_name(Arg_&& arg, Args_... args);
  197.   ::std::string* PROTOBUF_NONNULL mutable_name();
  198.   [[nodiscard]] ::std::string* PROTOBUF_NULLABLE release_name();
  199.   void set_allocated_name(::std::string* PROTOBUF_NULLABLE value);
  200.   private:
  201.   const ::std::string& _internal_name() const;
  202.   PROTOBUF_ALWAYS_INLINE void _internal_set_name(const ::std::string& value);
  203.   ::std::string* PROTOBUF_NONNULL _internal_mutable_name();
  204.   public:
  205.   // int32 age = 2;
  206.   void clear_age() ;
  207.   ::int32_t age() const;
  208.   void set_age(::int32_t value);
  209.   private:
  210.   ::int32_t _internal_age() const;
  211.   void _internal_set_age(::int32_t value);
  212.   public:
  213.   // @@protoc_insertion_point(class_scope:contact.Info)
  214. private:
  215.   class _Internal;
  216.   friend class ::google::protobuf::internal::TcParser;
  217.   static const ::google::protobuf::internal::TcParseTable<1, 2,
  218.                                    0, 25,
  219.                                    2>
  220.       _table_;
  221.   friend class ::google::protobuf::MessageLite;
  222.   friend class ::google::protobuf::Arena;
  223.   template <typename T>
  224.   friend class ::google::protobuf::Arena::InternalHelper;
  225.   using InternalArenaConstructable_ = void;
  226.   using DestructorSkippable_ = void;
  227.   struct Impl_ {
  228.     inline explicit constexpr Impl_(::google::protobuf::internal::ConstantInitialized) noexcept;
  229.     inline explicit Impl_(
  230.         ::google::protobuf::internal::InternalVisibility visibility,
  231.         ::google::protobuf::Arena* PROTOBUF_NULLABLE arena);
  232.     inline explicit Impl_(
  233.         ::google::protobuf::internal::InternalVisibility visibility,
  234.         ::google::protobuf::Arena* PROTOBUF_NULLABLE arena, const Impl_& from,
  235.         const Info& from_msg);
  236.     ::google::protobuf::internal::HasBits<1> _has_bits_;
  237.     ::google::protobuf::internal::CachedSize _cached_size_;
  238.     ::google::protobuf::internal::ArenaStringPtr name_;
  239.     ::int32_t age_;
  240.     PROTOBUF_TSAN_DECLARE_MEMBER
  241.   };
  242.   union { Impl_ _impl_; };
  243.   friend struct ::TableStruct_contact_2eproto;
  244. };
  245. extern const ::google::protobuf::internal::ClassDataFull Info_class_data_;
  246. // ===================================================================
  247. // ===================================================================
  248. #ifdef __GNUC__
  249. #pragma GCC diagnostic push
  250. #pragma GCC diagnostic ignored "-Wstrict-aliasing"
  251. #endif  // __GNUC__
  252. // -------------------------------------------------------------------
  253. // Info
  254. // string name = 1;
  255. inline void Info::clear_name() {
  256.   ::google::protobuf::internal::TSanWrite(&_impl_);
  257.   _impl_.name_.ClearToEmpty();
  258.   _impl_._has_bits_[0] &= ~0x00000001u;
  259. }
  260. inline const ::std::string& Info::name() const
  261.     ABSL_ATTRIBUTE_LIFETIME_BOUND {
  262.   // @@protoc_insertion_point(field_get:contact.Info.name)
  263.   return _internal_name();
  264. }
  265. template <typename Arg_, typename... Args_>
  266. PROTOBUF_ALWAYS_INLINE void Info::set_name(Arg_&& arg, Args_... args) {
  267.   ::google::protobuf::internal::TSanWrite(&_impl_);
  268.   _impl_._has_bits_[0] |= 0x00000001u;
  269.   _impl_.name_.Set(static_cast<Arg_&&>(arg), args..., GetArena());
  270.   // @@protoc_insertion_point(field_set:contact.Info.name)
  271. }
  272. inline ::std::string* PROTOBUF_NONNULL Info::mutable_name()
  273.     ABSL_ATTRIBUTE_LIFETIME_BOUND {
  274.   ::std::string* _s = _internal_mutable_name();
  275.   // @@protoc_insertion_point(field_mutable:contact.Info.name)
  276.   return _s;
  277. }
  278. inline const ::std::string& Info::_internal_name() const {
  279.   ::google::protobuf::internal::TSanRead(&_impl_);
  280.   return _impl_.name_.Get();
  281. }
  282. inline void Info::_internal_set_name(const ::std::string& value) {
  283.   ::google::protobuf::internal::TSanWrite(&_impl_);
  284.   _impl_._has_bits_[0] |= 0x00000001u;
  285.   _impl_.name_.Set(value, GetArena());
  286. }
  287. inline ::std::string* PROTOBUF_NONNULL Info::_internal_mutable_name() {
  288.   ::google::protobuf::internal::TSanWrite(&_impl_);
  289.   _impl_._has_bits_[0] |= 0x00000001u;
  290.   return _impl_.name_.Mutable( GetArena());
  291. }
  292. inline ::std::string* PROTOBUF_NULLABLE Info::release_name() {
  293.   ::google::protobuf::internal::TSanWrite(&_impl_);
  294.   // @@protoc_insertion_point(field_release:contact.Info.name)
  295.   if ((_impl_._has_bits_[0] & 0x00000001u) == 0) {
  296.     return nullptr;
  297.   }
  298.   _impl_._has_bits_[0] &= ~0x00000001u;
  299.   auto* released = _impl_.name_.Release();
  300.   if (::google::protobuf::internal::DebugHardenForceCopyDefaultString()) {
  301.     _impl_.name_.Set("", GetArena());
  302.   }
  303.   return released;
  304. }
  305. inline void Info::set_allocated_name(::std::string* PROTOBUF_NULLABLE value) {
  306.   ::google::protobuf::internal::TSanWrite(&_impl_);
  307.   if (value != nullptr) {
  308.     _impl_._has_bits_[0] |= 0x00000001u;
  309.   } else {
  310.     _impl_._has_bits_[0] &= ~0x00000001u;
  311.   }
  312.   _impl_.name_.SetAllocated(value, GetArena());
  313.   if (::google::protobuf::internal::DebugHardenForceCopyDefaultString() && _impl_.name_.IsDefault()) {
  314.     _impl_.name_.Set("", GetArena());
  315.   }
  316.   // @@protoc_insertion_point(field_set_allocated:contact.Info.name)
  317. }
  318. // int32 age = 2;
  319. inline void Info::clear_age() {
  320.   ::google::protobuf::internal::TSanWrite(&_impl_);
  321.   _impl_.age_ = 0;
  322.   _impl_._has_bits_[0] &= ~0x00000002u;
  323. }
  324. inline ::int32_t Info::age() const {
  325.   // @@protoc_insertion_point(field_get:contact.Info.age)
  326.   return _internal_age();
  327. }
  328. inline void Info::set_age(::int32_t value) {
  329.   _internal_set_age(value);
  330.   _impl_._has_bits_[0] |= 0x00000002u;
  331.   // @@protoc_insertion_point(field_set:contact.Info.age)
  332. }
  333. inline ::int32_t Info::_internal_age() const {
  334.   ::google::protobuf::internal::TSanRead(&_impl_);
  335.   return _impl_.age_;
  336. }
  337. inline void Info::_internal_set_age(::int32_t value) {
  338.   ::google::protobuf::internal::TSanWrite(&_impl_);
  339.   _impl_.age_ = value;
  340. }
  341. #ifdef __GNUC__
  342. #pragma GCC diagnostic pop
  343. #endif  // __GNUC__
  344. // @@protoc_insertion_point(namespace_scope)
  345. }  // namespace contact
  346. // @@protoc_insertion_point(global_scope)
  347. #include "google/protobuf/port_undef.inc"
  348. #endif  // contact_2eproto_2epb_2eh
复制代码
假如在main函数中需要对PersonInfo类进利用用,需要包含生成的头文件,别的在编译的时候,还需要指定使用-std=c++11选项以及编译连接库 -lprotobuf。
示例:
  1. #include<iostream>
  2. #include"contact.pb.h"
  3. #include<string>
  4. using std::endl;
  5. using std::cout;
  6. using std::cerr;
  7. int main()
  8. {
  9.     std::string people_str;
  10.     {
  11.         contact::PersonInfo info1;
  12.         info1.set_age(21);
  13.         info1.set_name("张三");
  14.         if(!info1.SerializeToString(&people_str))
  15.         {
  16.             cerr<<"序列化失败"<<endl;
  17.             exit(-1);
  18.         }        
  19.         cout<<"序列化成功"<<endl;
  20.         cout<<"people_str:"<<people_str<<endl;
  21.         cout<<"---------------------------------"<<endl;
  22.     }
  23.     {
  24.         contact::PersonInfo info1;
  25.         
  26.         if(!info1.ParseFromString(people_str))
  27.         {
  28.             cerr<<"反序列化失败"<<endl;
  29.             exit(-1);
  30.         }        
  31.         cout<<"反序列化成功"<<endl;
  32.         cout<<"name:"<<info1.name()<<endl;
  33.         cout<<"age:"<<info1.age()<<endl;
  34.     }
  35.     return 0;
  36. }
复制代码
运行结果:

4、在网络通讯或存储中使用protobuf序列化数据

和本地是类似的,这里不再演示,在反面的讲解和实际项目中再详细展示。

四、快速上手写一个小需求来熟悉怎样编写proto文件?

需求: 我们正在开发一个简单的图书管理体系。需要在客户端和服务器之间传输图书信息。每本图书包含以下内容:


  • 图书ID(整数)
  • 书名(字符串)
  • 作者(字符串)
  • 出书年份(整数,可选)
  • 是否借出(布尔值)
  • 借阅人(字符串,可选,仅在借出时填写)
请根据这个需求,设计一个合适的proto文件。

比较美满的答案如下:
  1. //声明语法版本
  2. syntax = "proto3";
  3. package books;
  4. // 单本图书信息
  5. message Book {
  6.     int64 id = 1;                  // 图书ID
  7.     string title = 2;              // 书名
  8.     string author = 3;             // 作者
  9.     int32 year = 4;                // 出版年份(可选,未知为0)
  10.     bool is_borrowed = 5;          // 是否借出
  11.     string borrower = 6;           // 借阅人(仅借出时填写,否则为空字符串)
  12. }
复制代码

完~

未经作者同意克制转载

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表