Looking for a MemoryStream in C ++

In the beautiful C # world, I can create a memory stream without specifying its size, write to it, and then just grab the base buffer.

How can I do the same in C ++? basically i need to do:

memory_stream  ms(GROW_AS_MUCH_AS_YOU_LIKE);

ms << someLargeObjects << someSmallObjects << someObjectsWhosSizeIDontKnow;

unsigned char* buffer = ms.GetBuffer();
int bufferSize = ms.GetBufferSize();

rawNetworkSocket.Send(buffer, bufferSize);

By the way, I have an incentive in my project, although I am not so familiar with it.

Thank.

+3
source share
4 answers
#include <sstream>

std::ostringstream  buffer; // no growth specification necessary
buffer << "a char buffer" << customObject << someOtherObject;

std::string contents = buffer.str();
size_t bufferSize = contents.size();

rawNetworkSocket.Send(contents); // you can take the size in Send

Using this approach, you will have to analyze the result in which you get it (since the code above simply converts your data into an unstructured string.

, ++ , < < . Custom:

template<typename C, typename T>
std::basic_ostream<C,T>& operator << (
    std::basic_ostream<C,T>& out, const Custom& object)
{
    out << object.member1 << "," << object.member2 /* ... */ << object.memberN;
    return out;
}

, boost:: serialization.

+5

std::stringstream . . ASCII, streambuf .

, ++ / , :

class unknown_base {
   virtual void dump( std::ostream & ) const;
};
std::ostream& operator<<( std::ostream& o, unknown_base const & obj ) {
   obj.dump( o );
   return o;
}
std::string serialize( std::vector<unknown_base*> const & data ) {
   std::ostringstream st;
   for ( std::vector<unknown_base*>::const_iterator it = data.begin(), end = data.end();
         it != end; ++it ) {
      st << **it; // double dereference: iterator, pointer
   }
   return st.str();
}
+2

Boost Iostreams, .

+1

, , - .

API , Google Protocol (protobuf ). ( ), API ++/Python/Java

:

  • , .
  • ( ), , , , ,
  • text / binary output. Text is convenient for debugging, binary is required when every bit counts

In addition, you can use the output of the text and compress it using LZO or one to get some space :)

0
source

Source: https://habr.com/ru/post/1751158/


All Articles