Analysis of implementation methods from protobuf C ++ serialize to char *

Source: Internet
Author: User

Protobuf demoProgramYes

The C ++ version of protubuf has several serialize and unserialize methods:

Method 1:

The official demo program uses

CopyCode The Code is as follows: // 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;

}

// 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;

}

The above uses fstream to compress data sequences (reverse sequences) into disk files.

If you want to sequence to char * and transmit it through socket, you can use:

Method 2:

Copy code The Code is as follows: int size = address_book.bytesize ();

Void * buffer = malloc (size );

Address_book.serializetoarray (buffer, size );

Method 3:

Copy code The Code is as follows: Use ostringstream,

STD: ostringstream stream;

Address_book.serializetoostream (& stream );

String text = stream. STR ();

Char * ctext = string. c_str ();

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.