Analysis of Google protocol buffers (III)

Source: Internet
Author: User

This article mainly introduces how to use Google protocol lib to serialize our data. There are many methods. This article only introduces three of them. Readers can explore other methods by themselves. But in general, serialization data is divided into the following two steps:

1) Fill the data structure with the data source, whether the data source comes from a file, memory, or standard input

2) serialize the data structure using the serialization interface provided by Lib, and store the data on the memory or disk.

I. Fill in the Data Structure 

Obtain data from the data source. The data source here may come from a file on the disk, a piece of data stored in the memory, or data from standard input. What we need to do is to fill in the fields in the addressbook data structure. In this example, the add_person function provided by addressbook is used to obtain a person pointer and fill it with the following code:CodeAs shown in:

// Address book data definition
Addressbook;

// Data Definition and initialization of the first contact
Person * Personme = Addressbook. add_person ();
Personme -> Set_id ( 1 );
Personme -> Set_name ( " Royal " );
Personme -> Set_email ( " Zwg19891129@163.com " );
Personme -> Set_unsure ( " 19bf173a0e87ab " );

// Data Definition and initialization of the second contact
Person * Personhim = Addressbook. add_person ();
Personhim -> Set_id ( 2 );
Personhim -> Set_name ( " Xxx " );
Personhim -> Set_email ( " XXX@XXX.com " );
Personhim -> Set_unsure ( " 19bf173a0e87ab " );

// Data Definition and initialization of personme mobile phone numbers
Person_phonenumber * Phonenumbermobile = Personme -> Add_phone ();
Phonenumbermobile -> Set_number ( " 15996110120 " );
Phonenumbermobile -> Set_type (person_phonetype_mobile );

// Data Definition and initialization of landline numbers for personme
Person_phonenumber * Phonenumberhome = Personme -> Add_phone ();
Phonenumberhome -> Set_number ( " 0256110120 " );
Phonenumberhome -> Set_type (person_phonetype_home );

// Data Definition and initialization of a number of personhim
Person_phonenumber * Phonenumberhim = Personhim -> Add_phone ();
Phonenumberhim -> Set_number ( " 15996111111 " );
Phonenumberhim -> Set_type (person_phonetype_home );

It is easy to see that the above Code adds two contacts to the address book, and then fills in the data information of each contact separately. The data in the address book is ready through the above Code.

Ii. serialize data 

In fact, by looking at the method name provided by the addressbook class generated by the compiler, You can roughly know which serialization methods are available, as shown below:

As you can see, there are many serialization methods available. In this article, we mainly use serializetostring, serializetocodedstream, and serializetoostream to complete serialization.

The following describes these methods:

1) serializetocodedstream Mode

First, we can know that the prototype of this function is bool serializetocodedstream (STD: ostream *). Therefore, to use this function, we need to combine the fstream of C ++. The Code is as follows:

// Method 1: Use serializepartialtoostream for serialization. Note that IOS: binary is written to a file using a binary stream.
Fstream fserial ( " Addressbook. Data " , IOS :: Out   | IOS: trunc | IOS: Binary );
If ( ! Addressbook. serializepartialtoostream ( & Fserial ))
{
Cerr < " Failed to serial address book data! \ N " ;
Return ;
}
Cout < " Serial address book data successfully! \ N " ;
Fserial. Close ();
Fserial. Clear ();

It can be seen that this method is quite convenient and concise, but it is difficult to control the encoding format of the output file, so you can use the method described below.

2) serializetostring

The function prototype is bool serializetostring (STD: string * output), so we can extract the data filled in the data structure addressbook and store it in a string object, then write the binary stream to the disk file. The Code is as follows:

File * G_addressbook = Fopen ( " Addressbook. Data " , " WB, CCS = Unicode " );
If (Null = G_addressbook)
{
Cerr < " Create addressbook. Data failed! \ N " ;
Return ;
}

String Serialstream =   "" ;
If ( ! Addressbook. serializepartialtostring ( & Serialstream ))
{
Cerr < " Failed to serial addressbook data! \ N " ;
Return ;
}

Fwrite (serialstream. c_str (), Sizeof ( Char ), Addressbook. bytesize (), g_addressbook );
Cout < " Serial address successfully! \ N " ;
If (G_addressbook)
{
Fclose (g_addressbook );
G_addressbook = NULL;
}  

The above code is a little tedious, but it is also a serialization method. By using the file operation function in the C library, you can more easily customize the output file.

3) serializetocodedstream Mode

This method mainly refers to a set of data stream operation objects provided in the Google buffer library. Some header files need to be introduced before using these objects, as shown below: 

# Include < Google / Protobuf / Io / Zero_copy_stream_impl.h >
# Include < Google / Protobuf / Io / Zero_copy_stream.h >
# Include < Google / Protobuf / Io / Coded_stream.h >  
Using   Namespace : Google: protobuf: IO;

This method also combines the open and Write Functions of the C library. The code for serialization is as follows:

Int FD = _ Open ( " Addressbook. Data " , _ O_wronly | _ O_creat | _ O_binary, _ s_iread | _ S_iwrite );
If ( - 1   = FD)
{
Cerr < " Create addressbook. Data failed! \ N " ;
Return ;
}
Char Tmparr [max_size];
Memset (tmparr, 0 , Sizeof (Tmparr ));
Zerocopyoutputstream * Raw_output =   New Arrayoutputstream (tmparr, addressbook. bytesize () + 1 );
Codedoutputstream * Coded_output =   New Codedoutputstream (raw_output );
If ( ! Addressbook. serializetocodedstream (coded_output ))
{
Cerr < " Fail to serial addressbook data! \ N " ;
Return ;
}
_ Write (FD, tmparr, addressbook. bytesize () + 1 );
Cout < " Serial address successfully! \ N " ;
Delete coded_output;
Delete raw_output;
Close (FD );

This article will introduce these three serialization methods for the moment, as well as methods such as serializetoarray and serializetofiledescriptor should be similar, so interested friends can try it on their own.

NextArticleI will introduce the deserialization method a little more, but it should not be too much content. After all, the methods are similar.

You are welcome to reprint the original article:Http://www.cnblogs.com/royenhomeThank you for your cooperation! 

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.