google protobuf使用

报错:libprotobuf ERROR external/com_google_protobuf/src/google/protobuf/descriptor_database.cc:393 analytics-zoo 在mac上的测试报错: [libprotobuf ERROR external/com_google_protobuf/src/google/protobuf/descriptor_database.cc:393] Invalid file descriptor data passed to EncodedDescriptorDatabase::Add(). [libprotobuf FATAL external/com_google_protobuf/src/google/pr 阅读详情

google protobuf使用

下载的是github上的:https://github.com/google/protobuf

 

If you get the source from github, you need to generate the configure script first:

$ ./autogen.sh

This will download gtest source (which is used for C++ Protocol Buffer unit-tests) to the current directory and run automake, autoconf, etc. to generate the configure script and various template makefiles.

运行这个会下载gtest(google单元测试框架)。由于google访问不了,这个这个没有成功。

 

直接在csdnhttp://download.youkuaiyun.com/download/canlets/6878023 下载的protobuf2.5.0.

tar zxvf protobuf-2.4.1.tar.gz
cd protobuf-2.4.1
./configure
make
make check
make install
安装结束。
验证:
查看是否安装成功:protoc --version
如果出现:libprotoc 2.4.1 则说明安装成功!
如果出现错误:

 

tar zxvf protobuf-2.5.0.tar.gz
 
./configure
make
make check
make install
安装结束。
验证:
查看是否安装成功:protoc --version
如果出现:libprotoc 2.5.0 则说明安装成功!
如果出现错误:
protoc: error while loading shared libraries: libprotobuf.so.0: cannot open
shared object file: No such file or directory
The issue is that Ubuntu 8.04 doesn't include /usr/local/lib in
library paths.
To fix it for your current terminal session, just type in
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

 

 安装完成后在终端下执行

  vim ~/.profile (我加在了/etc/profile里)

  打开配置文件,在该文件中添加

  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

  然后保存退出,接下来执行

  source ~/.profile

  是配置文件修改生效,最后执行

  protoc --version

  查看protobuf版本以测试是否安装成功

 

 

root@iZ23onhpqvwZ:~/ms/protobuf/protobuf-2.5.0# protoc --version
libprotoc 2.5.0

转:protobuf c++入门

1、在.proto文件中定义消息格式

2、使用protobuf编译器

3、使用c++ api来读写消息

 

windows  protobuf编译

我下载的是2.6.1的版本

打开vsprojects目录,里面有一个.sln文件,打开

vsprojects里面有一个readme.txt,告诉了如何安装:

复制代码

This directory contains project files for compiling Protocol Buffers using
MSVC.  This is not the recommended way to do Protocol Buffer development --
we prefer to develop under a Unix-like environment -- but it may be more
accessible to those who primarily work with MSVC.

Compiling and Installing
========================

1) Open protobuf.sln in Microsoft Visual Studio.
2) Choose "Debug" or "Release" configuration as desired.*
3) From the Build menu, choose "Build Solution".  Wait for compiling to finish.
4) From a command shell, run tests.exe and lite-test.exe and check that all
   tests pass.
5) Run extract_includes.bat to copy all the public headers into a separate
   "include" directory (under the top-level package directory).
6) Copy the contents of the include directory to wherever you want to put
   headers.
7) Copy protoc.exe wherever you put build tools (probably somewhere in your
   PATH).
8) Copy libprotobuf.lib, libprotobuf-lite.lib, and libprotoc.lib wherever you
   put libraries.

* To avoid conflicts between the MSVC debug and release runtime libraries, when
  compiling a debug build of your application, you may need to link against a
  debug build of libprotobuf.lib.  Similarly, release builds should link against
  release libs.

DLLs vs. static linking
=======================

Static linking is now the default for the Protocol Buffer libraries.  Due to
issues with Win32's use of a separate heap for each DLL, as well as binary
compatibility issues between different versions of MSVC's STL library, it is
recommended that you use static linkage only.  However, it is possible to
build libprotobuf and libprotoc as DLLs if you really want.  To do this,
do the following:

  1) Open protobuf.sln in MSVC.
  2) For each of the projects libprotobuf, libprotobuf-lite, and libprotoc, do
     the following:
    2a) Right-click the project and choose "properties".
    2b) From the side bar, choose "General", under "Configuration Properties".
    2c) Change the "Configuration Type" to "Dynamic Library (.dll)".
    2d) From the side bar, choose "Preprocessor", under "C/C++".
    2e) Add PROTOBUF_USE_DLLS to the list of preprocessor defines.
  3) When compiling your project, make sure to #define PROTOBUF_USE_DLLS.

When distributing your software to end users, we strongly recommend that you
do NOT install libprotobuf.dll or libprotoc.dll to any shared location.
Instead, keep these libraries next to your binaries, in your application's
own install directory.  C++ makes it very difficult to maintain binary
compatibility between releases, so it is likely that future versions of these
libraries will *not* be usable as drop-in replacements.

If your project is itself a DLL intended for use by third-party software, we
recommend that you do NOT expose protocol buffer objects in your library's
public interface, and that you statically link protocol buffers into your
library.

ZLib support
============

If you want to include GzipInputStream and GzipOutputStream
(google/protobuf/io/gzip_stream.h) in libprotoc, you will need to do a few
additional steps:

1) Obtain a copy of the zlib library.  The pre-compiled DLL at zlib.net works.
2) Make sure zlib's two headers are in your include path and that the .lib file
   is in your library path.  You could place all three files directly into the
   vsproject directory to compile libprotobuf, but they need to be visible to
   your own project as well, so you should probably just put them into the
   VC shared icnlude and library directories.
3) Right-click on the "tests" project and choose "properties".  Navigate the
   sidebar to "Configuration Properties" -> "Linker" -> "Input".
4) Under "Additional Dependencies", add the name of the zlib .lib file (e.g.
   zdll.lib).  Make sure to update both the Debug and Release configurations.
5) If you are compiling libprotobuf and libprotoc as DLLs (see previous
   section), repeat steps 2 and 3 for the libprotobuf and libprotoc projects.
   If you are compiling them as static libraries, then you will need to link
   against the zlib library directly from your own app.
6) Edit config.h (in the vsprojects directory) and un-comment the line that
   #defines HAVE_ZLIB.  (Or, alternatively, define this macro via the project
   settings.)

Notes on Compiler Warnings
==========================

The following warnings have been disabled while building the protobuf libraries
and compiler.  You may have to disable some of them in your own project as
well, or live with them.

C4018 - 'expression' : signed/unsigned mismatch
C4146 - unary minus operator applied to unsigned type, result still unsigned
C4244 - Conversion from 'type1' to 'type2', possible loss of data.
C4251 - 'identifier' : class 'type' needs to have dll-interface to be used by
        clients of class 'type2'
C4267 - Conversion from 'size_t' to 'type', possible loss of data.
C4305 - 'identifier' : truncation from 'type1' to 'type2'
C4355 - 'this' : used in base member initializer list
C4800 - 'type' : forcing value to bool 'true' or 'false' (performance warning)
C4996 - 'function': was declared deprecated

C4251 is of particular note, if you are compiling the Protocol Buffer library
as a DLL (see previous section).  The protocol buffer library uses templates in
its public interfaces.  MSVC does not provide any reasonable way to export
template classes from a DLL.  However, in practice, it appears that exporting
templates is not necessary anyway.  Since the complete definition of any
template is available in the header files, anyone importing the DLL will just
end up compiling instances of the templates into their own binary.  The
Protocol Buffer implementation does not rely on static template members being
unique, so there should be no problem with this, but MSVC prints warning
nevertheless.  So, we disable it.  Unfortunately, this warning will also be
produced when compiling code which merely uses protocol buffers, meaning you
may have to disable it in your code too.

复制代码

按照上面的很难成功,搞了n次,终与生成了,参考下面的。

http://blog.youkuaiyun.com/kandyer/article/details/10042715

0、为何使用protobuf?

 

1、原始内存数据结构,可以以二进制方式sent/saved.这种方式需要相同的内存布局和字节序。

2、以ad-hoc方式将数据项编码成一个简单字符串----比如,将4个int类型编码成"12:3:-23:67"。这种方式简灵活。适用于简单数据。

3、将数据序列化为XML。这种方式很流行,因为xml可读性好,编码解码方便,性能也好。仅仅XML dom树比较复杂。

 

protobuf可以很好的解决上述问题。你编写一个.proto文件来描述数据结构。protobuf编译器使用它创建一个类,使用二进制方式自动编码/解码该数据结构。生成的类提供getter/setter方法。

 

最重要的是,protobuf支持在此基础上进行格式扩展。

关于数据类型:

要通信,必须有协议,否则双方无法理解对方的码流。在protobuf中,协议是由一系列的消息组成的。因此最重要的就是定义通信时使用到的消息格式。

 

Protobuf消息定义

消息由至少一个字段组合而成,类似于C语言中的结构。每个字段都有一定的格式。

字段格式:限定修饰符① | 数据类型② | 字段名称③ | = | 字段编码值④ | [字段默认值⑤]

①.限定修饰符包含 required\optional\repeated

 

Required: 表示是一个必须字段,必须相对于发送方,在发送消息之前必须设置该字段的值,对于接收方,必须能够识别该字段的意思。发送之前没有设置required字段或者无法识别required字段都会引发编解码异常,导致消息被丢弃。

Optional:表示是一个可选字段,可选对于发送方,在发送消息时,可以有选择性的设置或者不设置该字段的值。对于接收方,如果能够识别可选字段就进行相应的处理,如果无法识别,则忽略该字段,消息中的其它字段正常处理。---因为optional字段的特性,很多接口在升级版本中都把后来添加的字段都统一的设置为optional字段,这样老的版本无需升级程序也可以正常的与新的软件进行通信,只不过新的字段无法识别而已,因为并不是每个节点都需要新的功能,因此可以做到按需升级和平滑过渡。

Repeated:表示该字段可以包含0~N个元素。其特性和optional一样,但是每一次可以包含多个值。可以看作是在传递一个数组的值。

 

②.数据类型

 

Protobuf定义了一套基本数据类型。几乎都可以映射到C++\Java等语言的基础数据类型.

      

protobuf 数据类型

描述

打包

C++语言映射

bool

布尔类型

1字节

bool

double

64位浮点数

N

double

float

32为浮点数

N

float

int32

32位整数、

N

int

uin32

无符号32位整数

N

unsigned int

int64

64位整数

N

__int64

uint64

64为无符号整

N

unsigned __int64

sint32

32位整数,处理负数效率更高

N

int32

sing64

64位整数 处理负数效率更高

N

__int64

fixed32

32位无符号整数

4

unsigned int32

fixed64

64位无符号整数

8

unsigned __int64

sfixed32

32位整数、能以更高的效率处理负数

4

unsigned int32

sfixed64

64为整数

8

unsigned __int64

string

只能处理 ASCII字符

N

std::string

bytes

用于处理多字节的语言字符、如中文

N

std::string

enum

可以包含一个用户自定义的枚举类型uint32

N(uint32)

enum

message

可以包含一个用户自定义的消息类型

N

object of class

N 表示打包的字节并不是固定。而是根据数据的大小或者长度。

例如int32,如果数值比较小,在0~127时,使用一个字节打包。

关于枚举的打包方式和uint32相同。

关于message,类似于C语言中的结构包含另外一个结构作为数据成员一样。

关于 fixed32 和int32的区别。fixed32的打包效率比int32的效率高,但是使用的空间一般比int32多。因此一个属于时间效率高,一个属于空间效率高。根据项目的实际情况,一般选择fixed32,如果遇到对传输数据量要求比较苛刻的环境,可以选择int32.

③.字段名称

 

字段名称的命名与C、C++、Java等语言的变量命名方式几乎是相同的。

protobuf建议字段的命名采用以下划线分割的驼峰式。例如 first_name 而不是firstName.

④.字段编码值

有了该值,通信双方才能互相识别对方的字段。当然相同的编码值,其限定修饰符和数据类型必须相同。

编码值的取值范围为 1~2^32(4294967296)。

其中 1~15的编码时间和空间效率都是最高的,编码值越大,其编码的时间和空间效率就越低(相对于1-15),当然一般情况下相邻的2个值编码效率的是相同的,除非2个值恰好实在4字节,12字节,20字节等的临界区。比如15和16.

1900~2000编码值为Google protobuf 系统内部保留值,建议不要在自己的项目中使用。

protobuf 还建议把经常要传递的值把其字段编码设置为1-15之间的值。

消息中的字段的编码值无需连续,只要是合法的,并且不能在同一个消息中有字段包含相同的编码值。

建议:项目投入运营以后涉及到版本升级时的新增消息字段全部使用optional或者repeated,尽量不实用required。如果使用了required,需要全网统一升级,如果使用optional或者repeated可以平滑升级。

 

⑤.默认值。当在传递数据时,对于required数据类型,如果用户没有设置值,则使用默认值传递到对端。当接受数据是,对于optional字段,如果没有接收到optional字段,则设置为默认值。

 

关于import

protobuf 接口文件可以像C语言的h文件一个,分离为多个,在需要的时候通过 import导入需要对文件。其行为和C语言的#include或者java的import的行为大致相同。

关于package

避免名称冲突,可以给每个文件指定一个package名称,对于java解析为java中的包。对于C++则解析为名称空间。

 

关于message

支持嵌套消息,消息可以包含另一个消息作为其字段。也可以在消息内定义一个新的消息。

关于enum

枚举的定义和C++相同,但是有一些限制。

枚举值必须大于等于0的整数。

使用分号(;)分隔枚举变量而不是C++语言中的逗号(,)

eg.

enum VoipProtocol 

{

    H323 = 1;

    SIP  = 2;

    MGCP = 3;

    H248 = 4;

}

 

 

 

示例

 

1、定义协议格式

复制代码

package tutorial;  message Person {
   required string name = 1;
   required int32 id = 2;
   optional string email = 3;
   
    enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
   }

   message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];   
   }

   repeated PhoneNumber phone = 4; 
}  

message AddressBook {
   repeated Person person = 1; 
}

复制代码

该结构与c++或java很像.

 

.proto文件以包声明开始,防止名字冲突。

简单类型:bool, int32, float, double, string.

其它类型:如上述的Person, PhoneNumber

 

类型可以嵌套。

“=1”, “=2”标识唯一“tag”.tag数1-15需要至少一个字节。

 

required: 必须设置它的值

optional: 可以设置,也可以不设置它的值

repeated: 可以认为是动态分配的数组

google工程师认为使用required威害更大, 他们更喜欢使用optional, repeated.

  

其中字段标签标示了字段在二进制流中存放的位置,这个是必须的,而且序列化与反序列化的时候相同的字段的Tag值必须对应,否则反序列化会出现意想不到的问题。

 

2、编译你的协议

 

运行protoc 来生成c++文件:

protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
  1. protoc proto文件路径 --cpp_out=C++代码文件导出目录  在使用中我发现有一点需要注意,就是--cpp_out的目录是根据proto文件的路径为基础的,也就是说:假设proto文件位于src目录下,希望将C++代码也导出到src目录下,那么--cpp_out直接=.就可以了。不需要再写一遍src/,如果写了src/,那么代码导出的目录将是src/src/(即使src/src不存在,也会被创建)

生成的文件为:

protoc --cpp_out=.    ./addressbook.proto 

 

addressbook.pb.h, 

addressbook.pb.cc

 

3、protobuf API

 整个头文件:

复制代码

// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: addressbook.proto

#ifndef PROTOBUF_addressbook_2eproto__INCLUDED
#define PROTOBUF_addressbook_2eproto__INCLUDED

#include <string>

#include <google/protobuf/stubs/common.h>

#if GOOGLE_PROTOBUF_VERSION < 2006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif

#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)

namespace tutorial {

// Internal implementation detail -- do not call these.
void  protobuf_AddDesc_addressbook_2eproto();
void protobuf_AssignDesc_addressbook_2eproto();
void protobuf_ShutdownFile_addressbook_2eproto();

class Person;
class Person_PhoneNumber;
class AddressBook;

enum Person_PhoneType {
  Person_PhoneType_MOBILE = 0,
  Person_PhoneType_HOME = 1,
  Person_PhoneType_WORK = 2
};
bool Person_PhoneType_IsValid(int value);
const Person_PhoneType Person_PhoneType_PhoneType_MIN = Person_PhoneType_MOBILE;
const Person_PhoneType Person_PhoneType_PhoneType_MAX = Person_PhoneType_WORK;
const int Person_PhoneType_PhoneType_ARRAYSIZE = Person_PhoneType_PhoneType_MAX + 1;

const ::google::protobuf::EnumDescriptor* Person_PhoneType_descriptor();
inline const ::std::string& Person_PhoneType_Name(Person_PhoneType value) {
  return ::google::protobuf::internal::NameOfEnum(
    Person_PhoneType_descriptor(), value);
}
inline bool Person_PhoneType_Parse(
    const ::std::string& name, Person_PhoneType* value) {
  return ::google::protobuf::internal::ParseNamedEnum<Person_PhoneType>(
    Person_PhoneType_descriptor(), name, value);
}
// ===================================================================

class Person_PhoneNumber : public ::google::protobuf::Message {
 public:
  Person_PhoneNumber();
  virtual ~Person_PhoneNumber();

  Person_PhoneNumber(const Person_PhoneNumber& from);

  inline Person_PhoneNumber& operator=(const Person_PhoneNumber& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const Person_PhoneNumber& default_instance();

  void Swap(Person_PhoneNumber* other);

  // implements Message ----------------------------------------------

  Person_PhoneNumber* New() const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const Person_PhoneNumber& from);
  void MergeFrom(const Person_PhoneNumber& from);
  void Clear();
  bool IsInitialized() const;

  int ByteSize() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  public:
  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // required string number = 1;
  inline bool has_number() const;
  inline void clear_number();
  static const int kNumberFieldNumber = 1;
  inline const ::std::string& number() const;
  inline void set_number(const ::std::string& value);
  inline void set_number(const char* value);
  inline void set_number(const char* value, size_t size);
  inline ::std::string* mutable_number();
  inline ::std::string* release_number();
  inline void set_allocated_number(::std::string* number);

  // optional .tutorial.Person.PhoneType type = 2 [default = HOME];
  inline bool has_type() const;
  inline void clear_type();
  static const int kTypeFieldNumber = 2;
  inline ::tutorial::Person_PhoneType type() const;
  inline void set_type(::tutorial::Person_PhoneType value);

  // @@protoc_insertion_point(class_scope:tutorial.Person.PhoneNumber)
 private:
  inline void set_has_number();
  inline void clear_has_number();
  inline void set_has_type();
  inline void clear_has_type();

  ::google::protobuf::UnknownFieldSet _unknown_fields_;

  ::google::protobuf::uint32 _has_bits_[1];
  mutable int _cached_size_;
  ::std::string* number_;
  int type_;
  friend void  protobuf_AddDesc_addressbook_2eproto();
  friend void protobuf_AssignDesc_addressbook_2eproto();
  friend void protobuf_ShutdownFile_addressbook_2eproto();

  void InitAsDefaultInstance();
  static Person_PhoneNumber* default_instance_;
};
// -------------------------------------------------------------------

class Person : public ::google::protobuf::Message {
 public:
  Person();
  virtual ~Person();

  Person(const Person& from);

  inline Person& operator=(const Person& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const Person& default_instance();

  void Swap(Person* other);

  // implements Message ----------------------------------------------

  Person* New() const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const Person& from);
  void MergeFrom(const Person& from);
  void Clear();
  bool IsInitialized() const;

  int ByteSize() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  public:
  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  typedef Person_PhoneNumber PhoneNumber;

  typedef Person_PhoneType PhoneType;
  static const PhoneType MOBILE = Person_PhoneType_MOBILE;
  static const PhoneType HOME = Person_PhoneType_HOME;
  static const PhoneType WORK = Person_PhoneType_WORK;
  static inline bool PhoneType_IsValid(int value) {
    return Person_PhoneType_IsValid(value);
  }
  static const PhoneType PhoneType_MIN =
    Person_PhoneType_PhoneType_MIN;
  static const PhoneType PhoneType_MAX =
    Person_PhoneType_PhoneType_MAX;
  static const int PhoneType_ARRAYSIZE =
    Person_PhoneType_PhoneType_ARRAYSIZE;
  static inline const ::google::protobuf::EnumDescriptor*
  PhoneType_descriptor() {
    return Person_PhoneType_descriptor();
  }
  static inline const ::std::string& PhoneType_Name(PhoneType value) {
    return Person_PhoneType_Name(value);
  }
  static inline bool PhoneType_Parse(const ::std::string& name,
      PhoneType* value) {
    return Person_PhoneType_Parse(name, value);
  }

  // accessors -------------------------------------------------------

  // required string name = 1;
  inline bool has_name() const;
  inline void clear_name();
  static const int kNameFieldNumber = 1;
  inline const ::std::string& name() const;
  inline void set_name(const ::std::string& value);
  inline void set_name(const char* value);
  inline void set_name(const char* value, size_t size);
  inline ::std::string* mutable_name();
  inline ::std::string* release_name();
  inline void set_allocated_name(::std::string* name);

  // required int32 id = 2;
  inline bool has_id() const;
  inline void clear_id();
  static const int kIdFieldNumber = 2;
  inline ::google::protobuf::int32 id() const;
  inline void set_id(::google::protobuf::int32 value);

  // optional string email = 3;
  inline bool has_email() const;
  inline void clear_email();
  static const int kEmailFieldNumber = 3;
  inline const ::std::string& email() const;
  inline void set_email(const ::std::string& value);
  inline void set_email(const char* value);
  inline void set_email(const char* value, size_t size);
  inline ::std::string* mutable_email();
  inline ::std::string* release_email();
  inline void set_allocated_email(::std::string* email);

  // repeated .tutorial.Person.PhoneNumber phone = 4;
  inline int phone_size() const;
  inline void clear_phone();
  static const int kPhoneFieldNumber = 4;
  inline const ::tutorial::Person_PhoneNumber& phone(int index) const;
  inline ::tutorial::Person_PhoneNumber* mutable_phone(int index);
  inline ::tutorial::Person_PhoneNumber* add_phone();
  inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >&
      phone() const;
  inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >*
      mutable_phone();

  // @@protoc_insertion_point(class_scope:tutorial.Person)
 private:
  inline void set_has_name();
  inline void clear_has_name();
  inline void set_has_id();
  inline void clear_has_id();
  inline void set_has_email();
  inline void clear_has_email();

  ::google::protobuf::UnknownFieldSet _unknown_fields_;

  ::google::protobuf::uint32 _has_bits_[1];
  mutable int _cached_size_;
  ::std::string* name_;
  ::std::string* email_;
  ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber > phone_;
  ::google::protobuf::int32 id_;
  friend void  protobuf_AddDesc_addressbook_2eproto();
  friend void protobuf_AssignDesc_addressbook_2eproto();
  friend void protobuf_ShutdownFile_addressbook_2eproto();

  void InitAsDefaultInstance();
  static Person* default_instance_;
};
// -------------------------------------------------------------------

class AddressBook : public ::google::protobuf::Message {
 public:
  AddressBook();
  virtual ~AddressBook();

  AddressBook(const AddressBook& from);

  inline AddressBook& operator=(const AddressBook& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const AddressBook& default_instance();

  void Swap(AddressBook* other);

  // implements Message ----------------------------------------------

  AddressBook* New() const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const AddressBook& from);
  void MergeFrom(const AddressBook& from);
  void Clear();
  bool IsInitialized() const;

  int ByteSize() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  public:
  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // repeated .tutorial.Person person = 1;
  inline int person_size() const;
  inline void clear_person();
  static const int kPersonFieldNumber = 1;
  inline const ::tutorial::Person& person(int index) const;
  inline ::tutorial::Person* mutable_person(int index);
  inline ::tutorial::Person* add_person();
  inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person >&
      person() const;
  inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person >*
      mutable_person();

  // @@protoc_insertion_point(class_scope:tutorial.AddressBook)
 private:

  ::google::protobuf::UnknownFieldSet _unknown_fields_;

  ::google::protobuf::uint32 _has_bits_[1];
  mutable int _cached_size_;
  ::google::protobuf::RepeatedPtrField< ::tutorial::Person > person_;
  friend void  protobuf_AddDesc_addressbook_2eproto();
  friend void protobuf_AssignDesc_addressbook_2eproto();
  friend void protobuf_ShutdownFile_addressbook_2eproto();

  void InitAsDefaultInstance();
  static AddressBook* default_instance_;
};
// ===================================================================


// ===================================================================

// Person_PhoneNumber

// required string number = 1;
inline bool Person_PhoneNumber::has_number() const {
  return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Person_PhoneNumber::set_has_number() {
  _has_bits_[0] |= 0x00000001u;
}
inline void Person_PhoneNumber::clear_has_number() {
  _has_bits_[0] &= ~0x00000001u;
}
inline void Person_PhoneNumber::clear_number() {
  if (number_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_->clear();
  }
  clear_has_number();
}
inline const ::std::string& Person_PhoneNumber::number() const {
  // @@protoc_insertion_point(field_get:tutorial.Person.PhoneNumber.number)
  return *number_;
}
inline void Person_PhoneNumber::set_number(const ::std::string& value) {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  number_->assign(value);
  // @@protoc_insertion_point(field_set:tutorial.Person.PhoneNumber.number)
}
inline void Person_PhoneNumber::set_number(const char* value) {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  number_->assign(value);
  // @@protoc_insertion_point(field_set_char:tutorial.Person.PhoneNumber.number)
}
inline void Person_PhoneNumber::set_number(const char* value, size_t size) {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  number_->assign(reinterpret_cast<const char*>(value), size);
  // @@protoc_insertion_point(field_set_pointer:tutorial.Person.PhoneNumber.number)
}
inline ::std::string* Person_PhoneNumber::mutable_number() {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  // @@protoc_insertion_point(field_mutable:tutorial.Person.PhoneNumber.number)
  return number_;
}
inline ::std::string* Person_PhoneNumber::release_number() {
  clear_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    return NULL;
  } else {
    ::std::string* temp = number_;
    number_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
    return temp;
  }
}
inline void Person_PhoneNumber::set_allocated_number(::std::string* number) {
  if (number_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    delete number_;
  }
  if (number) {
    set_has_number();
    number_ = number;
  } else {
    clear_has_number();
    number_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  }
  // @@protoc_insertion_point(field_set_allocated:tutorial.Person.PhoneNumber.number)
}

// optional .tutorial.Person.PhoneType type = 2 [default = HOME];
inline bool Person_PhoneNumber::has_type() const {
  return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Person_PhoneNumber::set_has_type() {
  _has_bits_[0] |= 0x00000002u;
}
inline void Person_PhoneNumber::clear_has_type() {
  _has_bits_[0] &= ~0x00000002u;
}
inline void Person_PhoneNumber::clear_type() {
  type_ = 1;
  clear_has_type();
}
inline ::tutorial::Person_PhoneType Person_PhoneNumber::type() const {
  // @@protoc_insertion_point(field_get:tutorial.Person.PhoneNumber.type)
  return static_cast< ::tutorial::Person_PhoneType >(type_);
}
inline void Person_PhoneNumber::set_type(::tutorial::Person_PhoneType value) {
  assert(::tutorial::Person_PhoneType_IsValid(value));
  set_has_type();
  type_ = value;
  // @@protoc_insertion_point(field_set:tutorial.Person.PhoneNumber.type)
}

// -------------------------------------------------------------------

// Person

// required string name = 1;
inline bool Person::has_name() const {
  return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Person::set_has_name() {
  _has_bits_[0] |= 0x00000001u;
}
inline void Person::clear_has_name() {
  _has_bits_[0] &= ~0x00000001u;
}
inline void Person::clear_name() {
  if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    name_->clear();
  }
  clear_has_name();
}
inline const ::std::string& Person::name() const {
  // @@protoc_insertion_point(field_get:tutorial.Person.name)
  return *name_;
}
inline void Person::set_name(const ::std::string& value) {
  set_has_name();
  if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    name_ = new ::std::string;
  }
  name_->assign(value);
  // @@protoc_insertion_point(field_set:tutorial.Person.name)
}
inline void Person::set_name(const char* value) {
  set_has_name();
  if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    name_ = new ::std::string;
  }
  name_->assign(value);
  // @@protoc_insertion_point(field_set_char:tutorial.Person.name)
}
inline void Person::set_name(const char* value, size_t size) {
  set_has_name();
  if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    name_ = new ::std::string;
  }
  name_->assign(reinterpret_cast<const char*>(value), size);
  // @@protoc_insertion_point(field_set_pointer:tutorial.Person.name)
}
inline ::std::string* Person::mutable_name() {
  set_has_name();
  if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    name_ = new ::std::string;
  }
  // @@protoc_insertion_point(field_mutable:tutorial.Person.name)
  return name_;
}
inline ::std::string* Person::release_name() {
  clear_has_name();
  if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    return NULL;
  } else {
    ::std::string* temp = name_;
    name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
    return temp;
  }
}
inline void Person::set_allocated_name(::std::string* name) {
  if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    delete name_;
  }
  if (name) {
    set_has_name();
    name_ = name;
  } else {
    clear_has_name();
    name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  }
  // @@protoc_insertion_point(field_set_allocated:tutorial.Person.name)
}

// required int32 id = 2;
inline bool Person::has_id() const {
  return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Person::set_has_id() {
  _has_bits_[0] |= 0x00000002u;
}
inline void Person::clear_has_id() {
  _has_bits_[0] &= ~0x00000002u;
}
inline void Person::clear_id() {
  id_ = 0;
  clear_has_id();
}
inline ::google::protobuf::int32 Person::id() const {
  // @@protoc_insertion_point(field_get:tutorial.Person.id)
  return id_;
}
inline void Person::set_id(::google::protobuf::int32 value) {
  set_has_id();
  id_ = value;
  // @@protoc_insertion_point(field_set:tutorial.Person.id)
}

// optional string email = 3;
inline bool Person::has_email() const {
  return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void Person::set_has_email() {
  _has_bits_[0] |= 0x00000004u;
}
inline void Person::clear_has_email() {
  _has_bits_[0] &= ~0x00000004u;
}
inline void Person::clear_email() {
  if (email_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    email_->clear();
  }
  clear_has_email();
}
inline const ::std::string& Person::email() const {
  // @@protoc_insertion_point(field_get:tutorial.Person.email)
  return *email_;
}
inline void Person::set_email(const ::std::string& value) {
  set_has_email();
  if (email_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    email_ = new ::std::string;
  }
  email_->assign(value);
  // @@protoc_insertion_point(field_set:tutorial.Person.email)
}
inline void Person::set_email(const char* value) {
  set_has_email();
  if (email_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    email_ = new ::std::string;
  }
  email_->assign(value);
  // @@protoc_insertion_point(field_set_char:tutorial.Person.email)
}
inline void Person::set_email(const char* value, size_t size) {
  set_has_email();
  if (email_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    email_ = new ::std::string;
  }
  email_->assign(reinterpret_cast<const char*>(value), size);
  // @@protoc_insertion_point(field_set_pointer:tutorial.Person.email)
}
inline ::std::string* Person::mutable_email() {
  set_has_email();
  if (email_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    email_ = new ::std::string;
  }
  // @@protoc_insertion_point(field_mutable:tutorial.Person.email)
  return email_;
}
inline ::std::string* Person::release_email() {
  clear_has_email();
  if (email_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    return NULL;
  } else {
    ::std::string* temp = email_;
    email_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
    return temp;
  }
}
inline void Person::set_allocated_email(::std::string* email) {
  if (email_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    delete email_;
  }
  if (email) {
    set_has_email();
    email_ = email;
  } else {
    clear_has_email();
    email_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  }
  // @@protoc_insertion_point(field_set_allocated:tutorial.Person.email)
}

// repeated .tutorial.Person.PhoneNumber phone = 4;
inline int Person::phone_size() const {
  return phone_.size();
}
inline void Person::clear_phone() {
  phone_.Clear();
}
inline const ::tutorial::Person_PhoneNumber& Person::phone(int index) const {
  // @@protoc_insertion_point(field_get:tutorial.Person.phone)
  return phone_.Get(index);
}
inline ::tutorial::Person_PhoneNumber* Person::mutable_phone(int index) {
  // @@protoc_insertion_point(field_mutable:tutorial.Person.phone)
  return phone_.Mutable(index);
}
inline ::tutorial::Person_PhoneNumber* Person::add_phone() {
  // @@protoc_insertion_point(field_add:tutorial.Person.phone)
  return phone_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >&
Person::phone() const {
  // @@protoc_insertion_point(field_list:tutorial.Person.phone)
  return phone_;
}
inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >*
Person::mutable_phone() {
  // @@protoc_insertion_point(field_mutable_list:tutorial.Person.phone)
  return &phone_;
}

// -------------------------------------------------------------------

// AddressBook

// repeated .tutorial.Person person = 1;
inline int AddressBook::person_size() const {
  return person_.size();
}
inline void AddressBook::clear_person() {
  person_.Clear();
}
inline const ::tutorial::Person& AddressBook::person(int index) const {
  // @@protoc_insertion_point(field_get:tutorial.AddressBook.person)
  return person_.Get(index);
}
inline ::tutorial::Person* AddressBook::mutable_person(int index) {
  // @@protoc_insertion_point(field_mutable:tutorial.AddressBook.person)
  return person_.Mutable(index);
}
inline ::tutorial::Person* AddressBook::add_person() {
  // @@protoc_insertion_point(field_add:tutorial.AddressBook.person)
  return person_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person >&
AddressBook::person() const {
  // @@protoc_insertion_point(field_list:tutorial.AddressBook.person)
  return person_;
}
inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person >*
AddressBook::mutable_person() {
  // @@protoc_insertion_point(field_mutable_list:tutorial.AddressBook.person)
  return &person_;
}


// @@protoc_insertion_point(namespace_scope)

}  // namespace tutorial

#ifndef SWIG
namespace google {
namespace protobuf {

template <> struct is_proto_enum< ::tutorial::Person_PhoneType> : ::google::protobuf::internal::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::tutorial::Person_PhoneType>() {
  return ::tutorial::Person_PhoneType_descriptor();
}

}  // namespace google
}  // namespace protobuf
#endif  // SWIG

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_addressbook_2eproto__INCLUDED

复制代码

 

生成的文件中有如下方法: 

复制代码

// name
  inline bool has_name() const;
  inline void clear_name();
  inline const ::std::string& name() const;
  inline void set_name(const ::std::string& value);
  inline void set_name(const char* value);
  inline ::std::string* mutable_name();

  // id
  inline bool has_id() const;
  inline void clear_id();
  inline int32_t id() const;
  inline void set_id(int32_t value);

  // email
  inline bool has_email() const;
  inline void clear_email();
  inline const ::std::string& email() const;
  inline void set_email(const ::std::string& value);
  inline void set_email(const char* value);
  inline ::std::string* mutable_email();

  // phone
  inline int phone_size() const;
  inline void clear_phone();
  inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >& phone() const;
  inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >* mutable_phone();
  inline const ::tutorial::Person_PhoneNumber& phone(int index) const;
  inline ::tutorial::Person_PhoneNumber* mutable_phone(int index);
  inline ::tutorial::Person_PhoneNumber* add_phone();

复制代码

4、枚举与嵌套类

 

生成的代码包含一个PhoneType枚举。Person::PhoneType, Person:MOBILE, Person::HOME, Person:WORK.

 

编译器生成的嵌套类称为Person::PhoneNumber. 实际生成类为Person_PhoneNumber.

 

5、标准方法

 

bool IsInitialized() const:                确认required字段是否被设置

string DebugString() const:                返回消息的可读表示,用于调试

void CopyFrom(const Person& from):         使用给定消息值copy

void Clear():                              清除所有元素为空状态

6、解析与序列化

 

bool SerializeToString(string* output) const:        序列化消息,将存储字节的以string方式输出。注意字节是二进制,而非文本;

bool ParseFromString(const string& data):            解析给定的string     

bool SerializeToOstream(ostream* output) const:      写消息给定的c++  ostream中

bool ParseFromIstream(istream* input):               从给定的c++ istream中解析出消息

7、protobuf和 oo设计

不要继承生成类并在此基础上添加相应的行为

 

8、写消息

 

示例:它从一个文件中读取AddressBook,基于io添加一个新的Person,并将新的AddressBook写回文件。

复制代码

#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person) {
  cout << "Enter person ID number: ";
  int id;
  cin >> id;
  person->set_id(id);
  cin.ignore(256, '\n');

  cout << "Enter name: ";
  getline(cin, *person->mutable_name());

  cout << "Enter email address (blank for none): ";
  string email;
  getline(cin, email);
  if (!email.empty()) {
    person->set_email(email);
  }

  while (true) {
    cout << "Enter a phone number (or leave blank to finish): ";
    string number;
    getline(cin, number);
    if (number.empty()) {
      break;
    }

    tutorial::Person::PhoneNumber* phone_number = person->add_phone();
    phone_number->set_number(number);

    cout << "Is this a mobile, home, or work phone? ";
    string type;
    getline(cin, type);
    if (type == "mobile") {
      phone_number->set_type(tutorial::Person::MOBILE);
    } else if (type == "home") {
      phone_number->set_type(tutorial::Person::HOME);
    } else if (type == "work") {
      phone_number->set_type(tutorial::Person::WORK);
    } else {
      cout << "Unknown phone type.  Using default." << endl;
    }
  }
}

// Main function:  Reads the entire address book from a file,
//   adds one person based on user input, then writes it back out to the same
//   file.
int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
    return -1;
  }

  tutorial::AddressBook address_book;

  {
    // Read the existing address book.
    fstream input(argv[1], ios::in | ios::binary);
    if (!input) {
      cout << argv[1] << ": File not found.  Creating a new file." << endl;
    } else if (!address_book.ParseFromIstream(&input)) {
      cerr << "Failed to parse address book." << endl;
      return -1;
    }
  }

  // Add an address.
  PromptForAddress(address_book.add_person());

  {
    // Write the new address book back to disk.
    fstream output(argv[1], ios::out | ios::trunc | ios::binary);
    if (!address_book.SerializeToOstream(&output)) {
      cerr << "Failed to write address book." << endl;
      return -1;
    }
  }

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

复制代码

 g++ addPerson.cpp  addressbook.pb.cc -o addPerson   -lpthread  -l protobuf

生成addPerson.

运行./addPerson addressbook1

 

注意使用GOOGLE_PROTOBUF_VERIFY_VERSION宏。每一个.pb.cc文件在启动时都将自动调用该宏。

 

注意在程序结尾处调用ShutdownProtobufLibrary()。

 

9、读消息 

复制代码

#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

// Iterates though all people in the AddressBook and prints info about them.
void ListPeople(const tutorial::AddressBook& address_book) {
  for (int i = 0; i < address_book.person_size(); i++) {
    const tutorial::Person& person = address_book.person(i);

    cout << "Person ID: " << person.id() << endl;
    cout << "  Name: " << person.name() << endl;
    if (person.has_email()) {
      cout << "  E-mail address: " << person.email() << endl;
    }

    for (int j = 0; j < person.phone_size(); j++) {
      const tutorial::Person::PhoneNumber& phone_number = person.phone(j);

      switch (phone_number.type()) {
        case tutorial::Person::MOBILE:
          cout << "  Mobile phone #: ";
          break;
        case tutorial::Person::HOME:
          cout << "  Home phone #: ";
          break;
        case tutorial::Person::WORK:
          cout << "  Work phone #: ";
          break;
      }
      cout << phone_number.number() << endl;
    }
  }
}

// Main function:  Reads the entire address book from a file and prints all
//   the information inside.
int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
    return -1;
  }

  tutorial::AddressBook address_book;

  {
    // Read the existing address book.
    fstream input(argv[1], ios::in | ios::binary);
    if (!address_book.ParseFromIstream(&input)) {
      cerr << "Failed to parse address book." << endl;
      return -1;
    }
  }

  ListPeople(address_book);

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

复制代码

g++ readPerson.cpp  addressbook.pb.cc -o readPerson   -lpthread  -l protobuf

运行:

./readPerson addressbook1
Person ID: 1
Name: suming
E-mail address: gz
Mobile phone #: 13631279712
Home phone #: 4578
Work phone #: 963
Work phone #: 65

10、扩展protobuf

 

如果希望向后兼容,必须遵循:

a、不必更改tag数

b、不必添加或删除任何required字段

c、可以删除optional或repeated字段

d、可以添加新的optional或repeated字段,但你必须使用新的tag数。

 

11、优化

c++的protobuf库,已经极大地优化了。合理使用可以改善性能。

a、如果可能,复用message对象。

b、关于多线程的内存分配器

 

12、高级用法

 

protobuf的消息类的一个关键特性是,反射(reflection)。可以使用xml或json来实现。参考。

 

 

================================================================

常见问题:

1、undefined reference to `pthread_once' 

使用-lpthread:

 

2、error while loading shared libraries: libprotobuf.so.7: cannot open shared object file: No such file or directory

使用-Wl,-Bstatic -lprotobuf -Wl,-Bdynamic -lpthread

 

 

参考:http://blog.youkuaiyun.com/zmzsoftware/article/details/17356199

 

一个简单的例子:

helloworld.proto

复制代码

package hw;
message helloworld
{
    required int32 id=1;//id
    required string str=2;//str
    optional int32  opt=3;//opt

}

复制代码

protoc -I=. --cpp_out=.   helloworld.proto

写序列化消息的进程

复制代码

#include"helloworld.pb.h"
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    hw::helloworld msg1;
    msg1.set_id(101);
    msg1.set_str("hello");
    
    fstream output("./log",ios::out| ios::trunc | ios::binary);
    if(! msg1.SerializeToOstream(&output))
    {
        cerr<<"Failed to write msg!"<<endl;
        return -1;
    }
    
    return 0;
}

复制代码

编译 write.cc 

 g++  msg.pb.cc write.cc -o write  `pkg-config --cflags --libs protobuf` -lpthread

 

执行write 

./write, 可以看到生成了log文件

root@iZ23onhpqvwZ:~/ms/protobuf/helloworld# xxd log 查看log二进制
0000000: 0865 1205 6865 6c6c 6f .e..hello

 

 

写反序列化的进程

reader.cc

复制代码

#include"helloworld.pb.h"
#include<iostream>
#include<fstream>
using namespace std;

void ListMsg(const hw::helloworld &msg)
{
    cout<<msg.id()<<endl;
    cout<<msg.str()<<endl;
}

int main(int argc,char **argv)
{
    hw::helloworld msg1;
    msg1.set_id(101);
    msg1.set_str("hello");
    
    fstream input("./log",ios::in | ios::binary);
    if(!msg1.ParseFromIstream(&input))
    {
       cerr<<"failed to parsed address book!";
       return -1;
    }
    
    ListMsg(msg1);
    return 0;
}

复制代码

编译:g++  msg.pb.cc reader.cc -o reader  `pkg-config --cflags --libs protobuf` -lpthread

执行./reader 输出 :

101

hello

 

makefile文件:

复制代码

all:write reader

clean:
    rm -f write reader helloworld.*.cc helloworld.*.h *.o log
    
proto_msg:
    protoc -I=. --cpp_out=.  helloworld.proto
    
write:helloworld.pb.cc write.cpp 
    g++ $^ -o  $@ -l protobuf -lpthread
reader:helloworld.pb.cc reader.cpp
    g++ $^ -o  $@ -l protobuf -lpthread
    

复制代码

参考了:http://www.cppblog.com/colorful/archive/2012/05/05/173761.html

 $@--目标文件,$^--所有的依赖文件,$<--第一个依赖文件。

protobuf 官方只有java、c++、Python的支持。

 

 ----------------------

一个例子:

关于Windows环境下protobuf初步学习指南

http://wenku.baidu.com/link?url=yAY8KF5lLV1LJa_yFwTygoizdUAZDB-l2bLa6IUN79q-xiogW8se1VKew9DIsSAa9o02m7F2XJPFananREd4jrxuUaVhan34Aw7qwGVr61K

 

讲解如何配置vs的:

VS2008下创建一个工程ProtoBuf,需要添加protobuf的头文件和lib文件。 
A.添加头文件操作:右击项目属性配置属性C/C++常规,右边附加包含目录。具体路径:H:\protobuf-2.4.1\protobuf-2.4.1\src 
B.添加库文件(lib)操作:右击项目属性配置属性链接器常规,右边附加库目录。具体路径:H:\protobuf-2.4.1\protobuf-2.4.1\vsprojects\Debug 
把person.pb.h和person.ph.cc放到工程ProtoBuf相应的头文件夹和源文件夹中

 

复制代码

#include<iostream>
#include"helloworld.pb.h"

#pragma comment(lib,"libprotobuf.lib")
#pragma comment(lib,"libprotoc.lib")

using namespace std;
using namespace Im;


int main(int argc, char **argv)
{
    helloworld msg1;
    msg1.set_id(100);
    msg1.set_str("sd");

    cout << msg1.id();
    cout << msg1.str();

}

复制代码

如果不想写

#pragma comment(lib,"libprotobuf.lib")
#pragma comment(lib,"libprotoc.lib")

有一种办法,项目配置-》链接器-》输入-》附加依赖性,增加
libprotobuf.lib
libprotoc.lib 也行。

http://my.oschina.net/cxh3905/blog/293000

http://blog.youkuaiyun.com/wangji163163/article/details/4455085

 

 

http://blog.sina.com.cn/s/blog_559f6ffc0101bo7u.html

protobuf socket:http://blog.youkuaiyun.com/monkey_d_meng/article/details/5894910

使用google protobuf的一个错误:[libprotobuff FATAL google/protobuf/generated_mesage_util.cc:783] CHECK... 早上程序都编译通过,一跑就报错,调试了半天,没有看出什么问题,对了半天协议,以为协议没有对齐,也没有什么问题. 后来发现居然是因为编译的时候没有链接pthread库,编译时-lpthread就不会有这个问题. 从他的报错根本看不出来问题是在哪里,哭了. ... 阅读详情

相关推荐

Vue TypeScript 使用eval函数的坑

正常情况下,项目里不会用eval函数,但是万一要调用一个全局的js库,就需要用eval做些骚操作,这个时候编译会提示: is strongly discouraged as it poses security risks and may cause issues with minification.警告是可以忽略,刚开始我也没当回事,有风险就有风险,可控,我知道自己写的是啥。但是,今天我改代码的时候遇到了出的问题。就是dev时候正常,但是打包以后,不按照预期执行,编译出来的代码就不是我要的逻辑。

jiyanglin的博客 8434

使用google protobuf编译时一个错误:libprotobuf FATAL google/protobuf/generated_message_util.cc:812

编译时链接上pthread库,即可编译成功。

qq_41897304的博客 1167

Google Protobuf 的使用

Google Protobuf的使用 Protobuf 数据序列化方式除了常见的JSON和XML之外,还有Google 的 ProtoBuf,它在效率、兼容性等方面非常的出色。 为什么选择Protobuf,可以看看官方文档给出的描述: protocol buffers 是一种语言无关、平台无关、可扩展的序列化结构数据的方法,它可用于(数据)通信协议、数据存储等。 Protocol Buffers 是一种灵活,高效,自动化机制的结构数据序列化方法-可类比 XML,但是比 XML 更小(3 ~ 10倍)、更快

ZJP的博客 870

C++ google protobuf

C++ google protobuf前言google::protobufgoogle::protobuf::io::ZeroCopyInputStreamgoogle::protobuf::io::IstreamInputStreamgoogle::protobuf::io::CodedInputStreamSetTotalBytesLimitgoogle::protobuf::io::Arra...

keineahnung2345的博客 3108

Google_Protobuf协议——Protobuf工具使用

编写Protobuf文件 编译Protobuf文件 工程源码加入Protobuf Linux Windows Debug Release 头文件包含 命名空间工具安装好后,就需要编写protobuf文件,让protobuf工具编译成源码,然后将源码放入工程文件中使用。protobuf文件的后缀为.proto编写Protobuf文件测试文件test.proto//确定支持的protobuf语法 syn

zxng_work的博客 4805

Google_Protobuf协议——Protobuf安装编译

文件版本说明 下载代码 linux下的编译安装 windows下的编译安装 Cmake编译 编译Release版本 编译Debug版本 Visual Studio 2017编译 编译Release版本 编译Debug版本 编译后的Protobuf工具 头文件包含 linux windows 库文件包含 Linux windows 版本编译文件版本说明 版本 颁布日期 修订章节 作者

zxng_work的博客 6902

Protobuf3 google protobuf

Protocol Buffers是一个跨语言、跨平台的具有可扩展机制的序列化数据工具。也就是说,我在ubuntu下用python语言序列化一个对象,并使用http协议传输到使用java语言的android客户端,java使用对用的代码工具进行反序列化,也可以得到对应的对象。听起来好像跟json没有多大区别。。。其实区别挺多的。 Google说protobuf是smaller,faster,simpler,我们使用google规定的proto协议定义语言,之后使用proto的工具对代码进行“编译”,生成对应的

dodouaj的专栏 2万+

Google ProtoBuf入门

Github 开发者文档~ Google ProtoBuf 是Google自己推出的一种序列化编码方式。 rotobuf是google推出的数据交换格式,相比xml、json主要优势在传输数据量更小、解析更快。它自带了一个编译器,可以编译成JAVA、python、C++代码。(来自官网的介绍~) 采用的Google自己推行的Base 128 Varints编码 简述 Base 128 Varints 编码: Varint是一种使用一个或多个字节序列化整数的方法。较小的数字占用较少的字节数。 除了最后一个字节

老宋的博客 682

google protobuf序列化原理

一、Java数据序列化大致有3种实现方式,1、JSON,2、Object Serialize,3、protobuf,今天重点解析第三种使用google protobuf的序列化原理。Protobuf的简单介绍、使用和分析一、protobuf是什么? protobuf(Google Protocol Buffers)是Google提供一个具有高效的协议数据交换格式工具库(类似Json

莫贤彬的博客 1万+

Google Protobuf的安装、配置、以及简单demo编译

【准备工作】 Google Protobuf安装包   https://code.google.com/p/protobuf/downloads/list 文档  https://developers.google.com/protocol-buffers/docs/overview?hl=zh-CN 项目首页 https://code.google.com/p/protobuf/

Allen的技术天空 1万+

开关电源环路学习笔记(1)-为啥要知道传递函数?

做硬件都会接触到开关电源,或多或少会接触到环路补偿。很多兄弟们也提出来让我说说这个,说明大家也都很关心,也说明这个好像有点难。 就我个人而言,我也想搞明白环路这一块,也查了一些资料,视频,不过说实话,一直都还是懵的,感觉很困难。 具体感觉就是,看资料或视频的时候,感觉好像是那么回事。但是撇开之后,就又云里雾里的感觉,总有一些想法没有找到答案。 问题 比如下面我想过的问题: 开关电源有开关,根本就不是一个线性系统,传递函数是咋弄出来的? 系统环路框图的输入量为什么不是Vin,而是参考电压V

weixin_42005993的博客 1万+

unity使用Google Protobuf

看到网上说Google的这个序列化工具能自动生成脚本(java、c#、c++。。。。。。)感觉很厉害的样子,于是就学学怎么在unity里用,正好结合之前写的socket通信,做一个demo。我看网上protobuf的教程很乱啊,最开始想找一篇跟着做下来完事了,结果坑也是不少。。。。。。 1.打开vs新建一个c#控制台工程 2.管理解决方案的nuget包 3.搜索Google protobuf ...

带酒书生的博客 2063

【天线与电波传播】电波传播部分 第7章 电波传播的基础知识3

菲涅尔区与菲涅尔带的基本知识

Chen59_2328的博客 1602

Node.js使用google-protobuf

随着Google的Protobuf3的发布,Google终于开发了一个可以给JavaScript使用的库。之前大家如果在node端使用了Protobuf应该用的是protobufjs这个库,但是既然Google官方支持了JavaScript,那么我们还是要去尝试一下的。 下面就开始介绍如何在node端使用google-protobuf,在解析生成proto数据的同时,我们也可以根据客户端请求的后

njweiyukun的博客 1万+

Multisim的探针(Probe)及数字电路的一些调试技巧的应用

Multisim的探针(Probe)及数字电路的一些调试技巧的应用 --EE Bang   By  WRS 上图为555方波发生器,根据R1,R2,C2参数的配置可产生频率为46.3KHZ,占空比50%的方波信号,如果用示波器查看波形参数的话需要用两个坐标轴做差,操作不便,另外如果要修改电路将上述电阻换成滑动变阻器的话,使其产生可变频率

Agent Christmas的博客 3万+

从0到1搭建StarRocks3.4.1存算一体架构(VM 虚拟机版)

本文详细介绍了如何在VM虚拟机上从零搭建StarRocks 3.4.1存算一体架构。首先阐述了StarRocks作为高性能分布式SQL数据仓库的优势,重点讲解了其存算一体架构的设计原理。随后提供完整的安装指南,包括环境准备(3台CentOS 8虚拟机配置)、网络互通验证、Java环境配置、软件包解压安装等关键步骤。文章特别详细说明了FE和BE节点的配置文件修改(fe.conf和be.conf)以及必要的防火墙端口开放配置。通过图文并茂的方式,帮助开发者和运维人员快速掌握StarRocks集群部署方法,为后续

小 tom的博客 1334

google protobuf 源码阅读(一)

文件: common.h,位于 src/google/protobuf/stubs 目录。下面·的代码是在阅读的时候,不太懂的地方,先记录下来。 (1)如下代码的意义 #ifdef _MSC_VER #define GOOGLE_LONGLONG(x) x##I64 #define GOOGLE_ULONGLONG(x) x##UI64 #define GOOGLE_LL_FORMAT

bluemaths的专栏 1755

国产数据库迁移必看:达梦到ES的CDC方案优化全记录(含完整代码)

本文详细记录了从达梦数据库到Elasticsearch的CDC方案优化全过程,涵盖触发器方案局限性、Debezium架构优势及完整代码实现。通过Flink集成和性能调优,实现毫秒级延迟同步,显著降低数据库负载,为国产数据库迁移提供可落地的技术方案。

weixin_29079671的博客 500

Google protobuf 协议的使用

Google protobuf 是一个高性能的通信协议,具有多语言支持,协议数据小,方便传输,高性能等特点。通过将数据序列化成二进制数组,并将二进制数组反序列化成数据对象。用于取代JSON,XML,作为服务器优秀的通信协议。 本文档的示例用JAVA编写 先去google的网站上下载protobuf 协议的支撑包地址:http://code.google.com/p/protobuf/downl

lovexiaozeng336的专栏 2659

YOLO11改进-模块-引入多尺度差异融合模块MDFM

MDFM主要用于融合双时相图像特征并生成带有丰富上下文信息的差异特征,其过程包含以下步骤:1. 特征提取与差异特征生成首先从双时相图像中提取特征f1和f2,然后将f1和f2进行像素级别的相减,再对相减结果取绝对值,最后通过一个3x3的卷积操作得到Di。2. 多尺度特征融合(MSFF)接着利用多尺度特征学习机制来增强特征融合效果。该机制通过不同核大小的卷积构建多尺度融合过程,具体是通过一个名为 MSFF 单元来实现的。

qq_64693987的博客 4380

基于Simulink的超级电容器充放电仿真

为了更好地理解和设计超级电容器的应用系统,通常需要进行详细的仿真分析。Simulink 提供了一个强大的仿真环境,可以用来设计、分析和验证超级电容器充放电系统的控制策略。本教程将详细介绍如何使用 Simulink 进行超级电容器充放电的仿真实例。如果你希望对超级电容器的充放电过程进行精确控制,可以添加一个简单的逻辑控制器来控制开关的状态。通过本教程,我们详细介绍了如何使用 Simulink 进行超级电容器充放电的仿真实例。2. 添加超级电容器模型。7. 添加控制器(可选)1. 调整超级电容器参数。

xiaoheshang_123的博客 519

google protobuf安装与使用

  google protobuf是一个灵活的、高效的用于序列化数据的协议。相比较XML和JSON格式,protobuf更小、更快、更便捷。google protobuf是跨语言的,并且自带了一个编译器(protoc),只需要用它进行编译,可以编译成Java、python、C++、C#、Go等代码,然后就可以直接使用,不需要再写其他代码,自带有解析的代码。更详细的介绍见:Protocol Buffers protobuf安装 1、下载protobuf代码google/protobuf 2、安装pr..

jusu10的博客 6020

ArcGIS与地理加权回归GWR【一】

因此,在实际问题研究中我们经常发现回归参数在不同地理位置上往往表现为不同,也就是说回归参数随地理位置变化,这时如果仍然采用全局空间回归模型(全局假设β是不会变得),得到的回归参数估计将是回归参数在整个研究区域内的平均值,如上所说某一个因素在ABC等不同的地理位置对房价的影响是不同的,假如采用全局空间回归模型,便忽略了数据的空间位置属性,只反映平均意义下因变量与自变量的相关关系,而不能有效反映回归关系的空间非平稳性的特征。当自变量为1个时,是一元线性回归,自变量为2个及以上时,称为多元线性回归。

JData_Engineer的博客 1376

Android Stduio中配置和使用Google Protobuf

和完整的配置:google()jcenter()google()jcenter()在app的build.gradle里面,需要配置:和已经sourceSets:main {java {proto {protobuf {protoc {java {}完整的App的build.gralde配置文件:android {main {java {proto {protobuf {protoc {java {}

2401_84148942的博客 907

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Google 的 Protobuf, 快就完事啦

例如,可以通过将公共字段放在一个单独的消息中,然后将这个消息作为另一个消息的字段来实现类似于类继承的功能。总之,在 Spring Boot 中使用 Protobuf 作为 Redis 的序列化和反序列化工具可以提高应用程序的性能和可扩展性。然而,在实际应用中,您可以通过上述方式在 Protobuf 中表示嵌套类、集合以及类似于类继承和接口实现的概念。在 Spring Boot 中使用 Protobuf 作为 Redis 的序列化和反序列化工具,首先需要添加相关的依赖,然后配置 RedisTemplate。

洪晓鸿 3266

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

上一篇: ZeroMQ实例-使用ZMQ(ZeroMQ)进行局域网内网络通信
下一篇: zeromq的使用
zero_china
博客等级 码龄16年 10粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值