Protocol Buffer Technology (c + + example) __c++

Source: Internet
Author: User
Tags object serialization

This blog is still based on Google's official document as the main line, the code example is completely taken from a demo project we are developing, through a period of previous attempts, the feeling that this combination of ways is more conducive to training and internal technical exchange. Or the words, there is no best, only the most suitable. I want to write a blog is also this reason, different technical topics may need to adopt a different style. Well, let's cut to the chase as soon as possible.

first, generate the target language code.
The following command helps us compile a set of protocol buffer-formatted messages defined in the Mymessage.proto file into the target language (c + +) code. As for the contents of the message, we will list them in the form of a fragment later, and all the source code will be given in the attachment.
Protoc-i=./message--cpp_out=./src./mymessage.proto
As you can see from the command line arguments above, the file to be compiled is Mymessage.proto, and he is stored in the message subdirectory of the current directory. The--cpp_out parameter indicates that the compilation tool we need to generate the target language is C + +, and the output directory is the SRC subdirectory of the current directory. In this case, the generated target code file name is Mymessage.pb.h and MyMessage.pb.cc.

Second, the C + + code generated by simple message.
Here we first define the simplest message, which contains only the fields of the original type.
Option optimize_for = Lite_runtime;
Message Logonreqmessage {
Required Int64 Acctid = 1;
Required String passwd = 2;
}
      The parent classes of all C + + classes generated by the. Proto file are:: Google Mymessage because we define the optimize_for value of the option in the file lite_runtime. Protobuf::messagelite, not:: Google::p rotobuf::message. In the previous blog has given some brief explanation, the Messagelite class is the message's parent class, in Messagelite will be missing protocol buffer to reflect the support, but this kind of function in the message class provides the concrete implementation. For our project, the entire system is relatively closed, does not interact with more external programs, while our client part is running on the Android platform, in view of this, we consider using the Lite version of Protocol Buffer. This will not only result in higher coding efficiency, but also less resources to be compiled by the generated code, and the flexibility and scalability of reflection can be completely ignored for this project. Let's take a look at some of the C + + class declarations generated by message logonreqmessage, as well as descriptive comments on common methods.

 1 class Logonreqmessage:public:: Google::p rotobuf::messagelite {2 public:3 logonreqmessage ();
 4 virtual ~logonreqmessage (); 5 6//Implements message----------------------------------------------7//The following member functions are all realized from the Messagelite in the virtual letter
 Number.
 8//Create a new Logonreqmessage object, equivalent to clone.
9 logonreqmessage* New () const; 10//The current object is initialized with another Logonreqmessage object, equivalent to an assignment operator overload (operator=) one void CopyFrom (const logonreqmessage& from)
;
12//Empty all the data in the current object, and set all member variables to an uninitialized state.
void Clear ();
14//Determine whether the current state has been initialized.
BOOL isinitialized () const;
16//After assigning a value to all the variables of the current object, gets the number of bytes required after the object is serialized.
int bytesize () const;
18//Gets the type name of the current object.
: £ std::string gettypename () const;
Int64//Required Acctid = 1;
22//The following member functions are generated because of the Acctid field defined in the message. 23//This static member represents the label value of the Acctid.
The naming rule is K + FieldName (Hump rule) + FieldNumber.
static const int kacctidfieldnumber = 1; 25         False if the Acctid field has been set to return true.
inline bool Has_acctid () const;
27//The Has_acctid function returns false after the function is executed, and the following Acctid function returns the default value of Acctid.
inline void Clear_acctid ();
29//Returns the current value of the Acctid field and returns the default value of the int64 type if there is no setting.
Inline:: Google::p rotobuf::int64 acctid () const;
31//Set a new value for the Acctid field, and the Has_acctid function returns True after the function is called.
inline void Set_acctid (:: Google::p rotobuf::int64 value);
N//Required String passwd = 2; 35//The following member functions are generated because of the passwd field defined in the message. The function generated here is basically similar to the set of functions above Acctid 36//generated.
So here's just a list of differences.
Panax notoginseng static const int kpasswdfieldnumber = 2;
inline bool has_passwd () const;
inline void clear_passwd ();
Inline const::std::string& passwd () const;
inline void set_passwd (const::std::string& value);
42//Set the variable value of the const char* type for the String Type field.
inline void set_passwd (const char* value);
inline void set_passwd (const char* value, size_t size); 45//You can assign a value directly to the Passwd object by the return value.
HAS_PASSWD returns True after the function is called.
Inline:: std::string* mutable_passwd (); 47//Releases the current object's ownership of the passwd field and returns the Passwd Field object pointer. After this function is called, the ownership of the Passwd Field object 48//is handed over to the caller.
False is returned after the HAS_PASSWD function is called again.
Inline:: std::string* release_passwd (); 
Private:51 ..... 52};

Here is the C + + test code and descriptive comment for the read-write Logonreqmessage object.

1     void Testsimplemessage ()
 2     {
 3         printf ("==================this is simple message.============ ====\n ");
 4         //Serializes the Logonreqmessage object to the specified memory area.
 5         Logonreqmessage Logonreq;
 6         Logonreq.set_acctid (a);
 7         logonreq.set_passwd ("Hello World");
 8//         early get the space occupied by the object serialization and make a one-time allocation, thus avoiding         the performance overhead caused by multiple allocation of 9//. In this way, the serialized data can also be encrypted.
to         be persisted or sent to the distal end.         int length = Logonreq.bytesize ();         char* buf = new Char[length];         Logonreq.serializetoarray (buf,length);
The         Logonreqmessage object is read and deserialized from memory, and the result is printed.
-         Logonreqmessage logonReq2;         Logonreq2.parsefromarray (buf,length);         printf ("Acctid =%i64d, password =%s\n", Logonreq2.acctid (), logonreq2.passwd (). C_STR ());         Delete [] buf;     }

C + + code generated by nested message.
Enum UserStatus {
OFFLINE = 0;
ONLINE = 1;
}
Enum Loginresult {
logon_result_success = 0;
Logon_result_notexist = 1;
LOGON_RESULT_ERROR_PASSWD = 2;
Logon_result_already_logon = 3;
Logon_result_server_error = 4;
}
Message UserInfo {
Required Int64 Acctid = 1;
Required String name = 2;
Required UserStatus status = 3;
}
Message Logonrespmessage {
Required Loginresult Logonresult = 1;
Required UserInfo UserInfo = 2; A userinfo message is nested here.
}
      for the C + + code generated by the above message, userinfo because it contains only the original Type field, so there is not much difference from the logonreqmessage in the previous example, and it is not listed here again. Because the UserInfo type of field is nested in the logonrespmessage message, here we will just give the C + + code and critical annotations generated by the message.

 1 class Logonrespmessage:public:: Google::p rotobuf::messagelite {2 Public:3
 Logonrespmessage ();
 4 virtual ~logonrespmessage (); 
 5 6//Implements message----------------------------------------------7 ...//This part of the function is the same as the previous example. 8 9//required.
Loginresult Logonresult = 1;
10//The following member functions are generated because of the Logonresult field defined in the message.    
11//This is basically the same as the previous example, except that the type Loginresult the enum type.
static const int klogonresultfieldnumber = 1;
inline bool Has_logonresult () const;
inline void Clear_logonresult ();
Inline Loginresult logonresult () const;
inline void Set_logonresult (loginresult value); //Required.
UserInfo UserInfo = 2; //
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.