Connect std :: istream directly to C-Array / unsigned char *

I am currently dealing with a custom buffer class that internally carries its data in a classic C array (unsigned char []).

To get better read / write access to this buffer, I was looking for a way to create a std :: istream object that is directly related to the contents of the POD ... otherwise like C-Array memory. The goal is to use all std :: stream formatters, and the actual "lorem ipsum" data should be written directly to the buffer. So something like this:

std::istream QuirkyBuffer::getIStream() { return std::istream(this->ptr, this->size); }

QuirkyBuffer d;
auto is = d.getIStream();
"lorem ipsum" >> is;

      

Can this be done?

+3


source to share


2 answers


You can use std::ostrstream

for this. It is outdated, but given its usefulness, I can't imagine it going away anytime soon.



Otherwise, it's very easy to write your own omemstream

.

+2


source


The end result is not a problem, the problem is in writing a streambuffer, because for example ifstream is just a class derived from istream and containing a streambuffer and some glue code. Now, to write a streambuffer, you need to override the private virtual input functions. I think underflow () and uflow () are fairly flat, but using these keywords you should be able to find the information you need on your own.



BTW: Streams are not copied unless changed in C ++ 11, so return by value is not-go.

+1


source







All Articles