How to serialize to raw block of memory?

It is very easy to serialize a C ++ object to a file with boost,

std::ofstream ofile( lpszFileName ); boost::archive::text_oarchive oa(ofile); oa << m_rgPoints; 

But how could I serialize a C ++ object to a raw block of memory?

Should I read the stream of the output file into memory, or is there any other better method?

Thanks.

+4
source share
3 answers

You can write your own streambuf class that works directly in your memory:

 class membuf : public std::streambuf { public: membuf( char * mem, size_t size ) { this->setp( mem, mem + size ); this->setg( mem, 0, mem + size ); } int_type overflow( int_type charval = traits_type::eof() ) { return traits_type::eof(); } int_type underflow( void ) { return traits_type::eof(); } int sync( void ) { return 0; } }; 

Use this class:

  membuf buf(address,size); ostream os(&buf); istream is(&buf); oss << "Write to the buffer"; 
+4
source

Edited in response to James Kanze's comments:

You can serialize in std::ostringstream :

 std::ostringstream oss; boost::archive::text_oarchive oa(oss); oa << m_rgPoints; 

And then read this, getting std::streambuf (calling oss.rdbuf() ) and calling streambuf::sgetn to read the data into its own buffer.

http://www.cplusplus.com/reference/iostream/ostringstream/rdbuf/

This avoids the unnecessary temporary file.

+4
source

If I understand, you need boost::archive::binary_oarchive binary serialization. Then you can copy data from the stream.

0
source

All Articles