Binary Memory Stream?

Hello there!

So basically I'm looking for functionality akin to std::ifstream and std::ofstream, but instead of writing\reading a file I want to write\read memory.

For instance, for writing, I would like to avoid having to malloc, realloc, and whatnot myself and have a stream and be able to do something like this:

uint64_t someVar = SomeNumber();
my_memory_stream.write( ( char* )&someVar, sizeof( someVar ) );

For each write call, it would do all the memory allocation it needs and I wouldn't have to worry about it. Then when I'm done writing that data, I can either copy it and free the data in the stream, or save a pointer to the data and just "close" the stream.

Something like:

void *pData = ( void* )my_memory_stream.data();
my_memory_stream.close();

Or something like:

size_t size = my_memory_stream.size();
void *pData = malloc( size );
std::memcpy( pData, ( void* )my_memory_stream.data(), size );
my_memory_stream.close_and_free();

// External code, remember to call free()!
DoStuffWithData( pData );

Is there some built in C++ functionality like that?
Last edited on
Maybe a stringstream (or its buffer) will have some of the functionality that you want.
http://www.cplusplus.com/reference/sstream/stringstream/

It's a memory store that you can read and write like a C++ filestream (or, indeed, any other stream, like cin and cout).

You don't have to do any memory management.
Last edited on
Someone on this forum (I don't remember who) provided a way to use streams based on char* memory buffers. This is only for fixed-size buffers, but you could modify this to do the allocation / reallocation that will be necessary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <istream>
#include <ostream>
#include <streambuf>

struct IMemBuf: std::streambuf
{
	IMemBuf(const char* base, size_t size)
	{
		char* p(const_cast<char*>(base));
		this->setg(p, p, p + size);
	}
};

struct IMemStream: virtual IMemBuf, std::istream
{
	IMemStream(const char* mem, size_t size) :
		IMemBuf(mem, size),
		std::istream(static_cast<std::streambuf*>(this))
	{
	}
};

struct OMemBuf: std::streambuf
{
	OMemBuf(char* base, size_t size)
	{
		this->setp(base, base + size);
	}
};

struct OMemStream: virtual OMemBuf, std::ostream
{
	OMemStream(char* base, size_t size) :
		OMemBuf(mem, size),
		std::ostream(static_cast<std::streambuf*>(this))
	{
	}
};


Note: I modified for my own purposes the code that was originally presented. I think I removed all of my own specific code, so this should be what was originally presented.

Registered users can post here. Sign in or register to post.