- 浏览: 170323 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
boz.lee:
不错, 好多地方因为这里而出错
全局变量和局部变量在内存里的区别 -
issllx:
看到此文后对iteye深表遗憾
Yahoo S4 -
wohenshuaiba:
请问你有这个的代码吗?
k均值聚类(K-means) -
yxwang0615:
大神:
apr-1.3.3.tar.bz2
apr-util- ...
log4cxx编译方法 -
yxwang0615:
比csdn上的说的清楚干练,早看到这个就好了,我编了一天
p ...
log4cxx编译方法
This tutorial provides a basic C++ programmer's introduction to working with protocol buffers. By walking through creating a simple example application, it shows you how to This isn't a comprehensive guide to using protocol buffers in C++. For more detailed reference information, see the Protocol Buffer Language Guide, the C++ API Reference, the C++ Generated Code Guide, and the Encoding Reference. The example we're going to use is a very simple "address book" application that can read and write people's contact details to and from a file. Each person in the address book has a name, an ID, an email address, and a contact phone number. How do you serialize and retrieve structured data like this? There are a few ways to solve this problem: Protocol buffers are the flexible, efficient, automated solution to solve exactly this problem. With protocol buffers, you write a The example code is included in the source code package, under the "examples" directory. Download it here. To create your address book application, you'll need to start with a As you can see, the syntax is similar to C++ or Java. Let's go through each part of the file and see what it does. The Next, you have your message definitions. A message is just an aggregate containing a set of typed fields. Many standard simple data types are available as field types, including The " = 1", " = 2" markers on each element identify the unique "tag" that field uses in the binary encoding. Tag numbers 1-15 require one less byte to encode than higher numbers, so as an optimization you can decide to use those tags for the commonly used or repeated elements, leaving tags 16 and higher for less-commonly used optional elements. Each element in a repeated field requires re-encoding the tag number, so repeated fields are particularly good candidates for this optimization. Each field must be annotated with one of the following modifiers: Required Is Forever You should be very careful about marking fields as You'll find a complete guide to writing Now that you have a This generates the following files in your specified destination directory: Let's look at some of the generated code and see what classes and functions the compiler has created for you. If you look in As you can see, the getters have exactly the name as the field in lowercase, and the setter methods begin with While the numeric Repeated fields also have some special methods – if you look at the methods for the repeated For more information on exactly what members the protocol compiler generates for any particular field definition, see the C++ generated code reference. The generated code includes a The compiler has also generated a nested class for you called Each message class also contains a number of other methods that let you check or manipulate the entire message, including: These and the I/O methods described in the following section implement the Finally, each protocol buffer class has methods for writing and reading messages of your chosen type using the protocol buffer binary format. These include: These are just a couple of the options provided for parsing and serialization. Again, see the Protocol Buffers and O-O Design Protocol buffer classes are basically dumb data holders (like structs in C++); they don't make good first class citizens in an object model. If you want to add richer behaviour to a generated class, the best way to do this is to wrap the generated protocol buffer class in an application-specific class. Wrapping protocol buffers is also a good idea if you don't have control over the design of the Now let's try using your protocol buffer classes. The first thing you want your address book application to be able to do is write personal details to your address book file. To do this, you need to create and populate instances of your protocol buffer classes and then write them to an output stream. Here is a program which reads an Protocol Buffer Basics: C++
.proto
file.Why Use Protocol Buffers?
.proto
description of the data structure you wish to store. From that, the protocol buffer compiler creates a class that implements automatic encoding and parsing of the protocol buffer data with an efficient binary format. The generated class provides getters and setters for the fields that make up a protocol buffer and takes care of the details of reading and writing the protocol buffer as a unit. Importantly, the protocol buffer format supports the idea of extending the format over time in such a way that the code can still read data encoded with the old format.Where to Find the Example Code
Defining Your Protocol Format
.proto
file. The definitions in a .proto
file are simple: you add a message for each data structure you want to serialize, then specify a name and a type for each field in the message. Here is the .proto
file that defines your messages, addressbook.proto
.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;
}
.proto
file starts with a package declaration, which helps to prevent naming conflicts between different projects. In C++, your generated classes will be placed in a namespace matching the package name.bool
, int32
, float
, double
, and string
. You can also add further structure to your messages by using other message types as field types – in the above example the Person
message contains PhoneNumber
messages, while the AddressBook
message contains Person
messages. You can even define message types nested inside other messages – as you can see, the PhoneNumber
type is defined inside Person
. You can also define enum
types if you want one of your fields to have one of a predefined list of values – here you want to specify that a phone number can be one of MOBILE
, HOME
, or WORK
.
required
: a value for the field must be provided, otherwise the message will be considered "uninitialized". If libprotobuf
is compiled in debug mode, serializing an uninitialized message will cause an assertion failure. In optimized builds, the check is skipped and the message will be written anyway. However, parsing an uninitialized message will always fail (by returning false
from the parse method). Other than this, a required field behaves exactly like an optional field.optional
: the field may or may not be set. If an optional field value isn't set, a default value is used. For simple types, you can specify your own default value, as we've done for the phone number type
in the example. Otherwise, a system default is used: zero for numeric types, the empty string for strings, false for bools. For embedded messages, the default value is always the "default instance" or "prototype" of the message, which has none of its fields set. Calling the accessor to get the value of an optional (or required) field which has not been explicitly set always returns that field's default value.repeated
: the field may be repeated any number of times (including zero). The order of the repeated values will be preserved in the protocol buffer. Think of repeated fields as dynamically sized arrays.required
. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required
does more harm than good; they prefer to use only optional
and repeated
. However, this view is not universal..proto
files – including all the possible field types – in the Protocol Buffer Language Guide. Don't go looking for facilities similar to class inheritance, though – protocol buffers don't do that.Compiling Your Protocol Buffers
.proto
, the next thing you need to do is generate the classes you'll need to read and write AddressBook
(and hence Person
and PhoneNumber
) messages. To do this, you need to run the protocol buffer compiler protoc
on your .proto
:
$SRC_DIR
), and the path to your .proto
. In this case, you...:
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
Because you want C++ classes, you use the --cpp_out
option – similar options are provided for other supported languages.
addressbook.pb.h
, the header which declares your generated classes.addressbook.pb.cc
, which contains the implementation of your classes.The Protocol Buffer API
tutorial.pb.h
, you can see that you have a class for each message you specified in tutorial.proto
. Looking closer at the Person
class, you can see that the complier has generated accessors for each field. For example, for the name
, id
, email
, and phone
fields, you have these methods: // 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();
set_
. There are also has_
methods for each singular (required or optional) field which return true if that field has been set. Finally, each field has a clear_
method that un-sets the field back to its empty state.id
field just has the basic accessor set described above, the name
and email
fields have a couple of extra methods because they're strings – amutable_
getter that lets you get a direct pointer to the string, and an extra setter. Note that you can call mutable_email()
even if email
is not already set; it will be initialized to an empty string automatically. If you had a singular message field in this example, it would also have a mutable_
method but not a set_
method.phone
field, you'll see that you can
_size
(in other words, how many phone numbers are associated with this Person
).add_
that just lets you pass in the new value).Enums and Nested Classes
PhoneType
enum that corresponds to your .proto
enum. You can refer to this type as Person::PhoneType
and its values asPerson::MOBILE
, Person::HOME
, and Person::WORK
(the implementation details are a little more complicated, but you don't need to understand them to use the enum).Person::PhoneNumber
. If you look at the code, you can see that the "real" class is actually calledPerson_PhoneNumber
, but a typedef defined inside Person
allows you to treat it as if it were a nested class. The only case where this makes a difference is if you want to forward-declare the class in another file – you cannot forward-declare nested types in C++, but you can forward-declare Person_PhoneNumber
.Standard Message Methods
bool IsInitialized() const;
: checks if all the required fields have been set.string DebugString() const;
: returns a human-readable representation of the message, particularly useful for debugging.void CopyFrom(const Person& from);
: overwrites the message with the given message's values.void Clear();
: clears all the elements back to the empty state.Message
interface shared by all C++ protocol buffer classes. For more info, see thecomplete API documentation for Message
.Parsing and Serialization
bool SerializeToString(string* output) const;
: serializes the message and stores the bytes in the given string. Note that the bytes are binary, not text; we only use the string
class as a convenient container.bool ParseFromString(const string& data);
: parses a message from the given string.bool SerializeToOstream(ostream* output) const;
: writes the message to the given C++ ostream
.bool ParseFromIstream(istream* input);
: parses a message from the given C++ istream
.Message
API reference for a complete list..proto
file (if, say, you're reusing one from another project). In that case, you can use the wrapper class to craft an interface better suited to the unique environment of your application: hiding some data and methods, exposing convenience functions, etc. You should never add behaviour to the generated classes by inheriting from them. This will break internal mechanisms and is not good object-oriented practice anyway.Writing A Message
AddressBook
from a file, adds one new Person
to it based on user input, and writes the new AddressBook
back out to the file again. The parts which directly call or reference code generated by the protocol compiler are highlighted.#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] << <
发表评论
-
小对象的分配技术
2011-03-21 12:01 1451小对象分配技术是Loki提高效率的有效途径,Loki里广 ... -
Techniques of Protocol Buffers Developer Guide
2010-12-07 10:39 1110Techniques Streaming Multip ... -
Encoding of Protocol Buffers Developer Guide
2010-12-07 10:37 934Encoding A Simple Message ... -
Style Guide of Protocol Buffers Developer Guide
2010-12-07 10:36 777Style Guide This document pr ... -
Language Guide of Protocol Buffers Developer Guide
2010-12-07 10:34 1042Language Guide Defining A M ... -
Overview of Protocol Buffers Developer Guide
2010-12-07 10:31 672Developer Guide Welcome to t ... -
字节序
2010-12-01 21:03 943这几天又开始做网络方面的应用了,既然是网络编程,字节序肯定 ... -
全局变量和局部变量在内存里的区别
2010-11-09 21:55 2203一、预备知识—程序的内存分配 一个由c/C++编译 ... -
JobFlow要继续考虑的问题
2010-09-17 22:35 935小记: 1.把作业队列的概念扩展为作业池JobPool,提供 ... -
C++单例不可继承
2010-09-17 17:24 1476C++语言和单例的特性决定了单例不可继承。 单例有如下几项要 ... -
C++静态成员与静态成员函数小结
2010-09-16 15:48 1047类中的静态成员真是个让人爱恨交加的特性。我决定好好总结一下静态 ... -
log4cxx编译方法
2010-09-08 10:30 19731、下载http://logging.apache.o ... -
优秀的框架工具
2010-09-08 10:13 1125zookeeper Hadoop的子项目,可靠地分布式小文件 ... -
关于auto_ptr的忠告
2010-08-26 16:21 9091.auto_ptr不能用于数组,因为它调用的是delet ... -
snprintf与strncpy效率对比
2010-07-20 09:31 1565一直以为strncpy效率优于snprintf. 无意中在网上 ... -
用Valgrind查找内存泄漏和无效内存访问
2010-07-20 09:29 1946Valgrind是x86架构Linux上的多重用途代码剖析和内 ... -
头文件互包含于名字空间的相关问题
2010-07-17 20:27 1045c/c++里面头文件的使用 ... -
C++库介绍
2010-04-02 16:30 1498基础类1、 Dinkumware C++ ... -
C++中头文件相互包含的几点问题
2010-04-02 16:29 1014一、类嵌套的疑问 C++ ...
相关推荐
#### Protocol_Buffer Basics: Java - **定义proto文件**:首先定义消息类型。 - **编译Protocol_Buffer文件**:使用特定语言环境下的编译器生成对应的代码。 - **Protocol_Buffer API使用**:学习如何使用生成的...
Python Basics: A Self-Teaching Introduction By 作者: H. Bhasin ISBN-10 书号: 1683923537 ISBN-13 书号: 9781683923534 出版日期: 2018-12-17 pages 页数: (604) Python has become the language of choice ...
Blockchain Basics: A Non-Technical Introduction in 25 Steps By 作者: Daniel Drescher ISBN-10 书号: 1484226038 ISBN-13 书号: 9781484226032 Edition 版本: 1st ed. 出版日期: 2017-03-16 pages 页数: (276 ) ...
Blockchain Basics A Non-Technical Introduction in 25 Steps 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
### IC Layout基础知识详解 #### 基本电路理论回顾与半导体材料介绍 在《IC Layout基础知识:实用指南》这本书中,作者Christopher Saint 和 Judy Saint 为读者提供了深入了解集成电路(Integrated Circuit, IC)...
`django-auth-basics`项目,正如其标题所示,是针对Django身份验证基础知识的一个详细解释,旨在帮助初学者更好地理解和应用Django的认证机制。 **Django身份验证系统组件** 1. **User模型**:Django提供了一个...
根据给定的文件信息,我们可以总结出以下关于“交大C++编程课件 1.C++ Basics”的相关知识点: ### C++ 基础 #### 1. 引言 - **C++ 起源**:C++ 是由 Bjarne Stroustrup 在贝尔实验室开发的一种面向对象的编程语言...
HANA是一个软硬件结合体,提供高性能的数据查询功能,用户可以直接对大量实时业务数据进行查询和分析,而不需要对业务数据进行建模、聚合等。
FFmpeg 官方推荐书目(英文版): Brief Contents Introduction 12 1. FFmpeg Fundamentals 15 2. Displaying Help and Features 29 3. Bit Rate, Frame Rate and File Size 60 4. Resizing and Scaling Video 64 ...
"C-C17-Basics:C++基本代码"这个资源包显然旨在帮助初学者理解和掌握C++的基础编程概念。让我们深入探讨其中涉及的一些关键知识点。 1. **循环**: - `for`循环:C++中的for循环用于执行固定次数的迭代,通常在...
`Rcpp`和`RcppArmadillo`是R语言与C++交互的库,它们使得BASiCS能够在底层使用高效的C++代码,提高计算速度,特别是处理大规模数据集时。`Rcpp`提供了一种无缝的方式将C++代码集成到R环境中,而`RcppArmadillo`则是...
使用C#开发应用程序simpler than using C++ ,因为language syntax is simpler 。 尽管如此,C#是一种powerful language 。 C#只是.NET development one of the languages available ,但是它无疑是最好的。 它...
NodeJs_Basics:这是一个致力于学习NOdejs的项目
graphql-basics:GraphQL学习基础
matlab中存档算法代码机器学习基础研讨会 该研讨会的目的是回顾有关机器学习的最基本主题并实现基本的线性回归模型。 设置 对于这个wirkshop,我们需要一种数值演算编程语言,为此,我们可以使用以下选项: ...
本教程“MySQL_basics:geekbarains MySQL基础”旨在为初学者提供一个全面的起点,了解MySQL的核心概念和操作。 1. **安装与配置** - 安装MySQL服务器:在不同的操作系统(如Windows、Linux和Mac OS)上安装MySQL的...
从谷歌官网下载一些文件,Encoding.txt, Java Generated Code.txt,Language Guide.txt,Protocol Buffer Basics Java.txt,Style Guide.txt。
LoRa Basics:trade_mark:站是LoRaWAN网关的实现,包括以下功能为LoRaWAN A,B和C类做好准备支持集中器参考设计 , 和统一无线电抽象层强大的后端协议(和阅读) 集中更新和配置管理集中的渠道计划管理集中时间同步和...