Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stl stringstream direct buffer access

Tags:

c++

stl

this should be pretty common yet I find it fascinating that I couldn't find any straight forward solution.

Basically I read in a file over the network into a stringstream. This is the declaration:

std::stringstream membuf(std::ios::in | std::ios::out | std::ios::binary); 

Now I have some C library that wants direct access to the read chunk of the memory. How do I get that? Read only access is OK. After the C function is done, I dispose of the memorystream, no need for it.

str() copies the buffer, which seems unnecessary and doubles the memory.

Am I missing something obvious? Maybe a different stl class would work better.

Edit: Apparently, stringstream is not guaranteed to be stored continuously. What is?

if I use vector<char> how do I get byte buffer?

like image 770
Kugel Avatar asked Dec 09 '09 22:12

Kugel


1 Answers

You can take full control of the buffer used by writing the buffer yourself and using that buffer in the stringstream

stringstream membuf(std::ios::in | std::ios::out | std::ios::binary); membuf.rdbuf(yourVeryOwnStreamBuf); 

Your own buffer should be derived from basic_streambuf, and override the sync() and overflow() methods appropriately.

For your internal representation you could probably use something like vector< char >, and reserve() it to the needed size so that no reallocations and copies are done.

This implies you know an upper bound for the space needed in advance. But if you don't know the size in advance, and need a continguous buffer in the end, copies are of course unavoidable.

like image 136
Pieter Avatar answered Sep 18 '22 17:09

Pieter