Subject: Re: [boost] [iostreams] binary memory stream
From: Kenny Riddile (kfriddile_at_[hidden])
Date: 2009-03-30 12:17:57


Chris Weed wrote:
> On Sun, Mar 29, 2009 at 9:10 PM, Kenny Riddile <kfriddile_at_[hidden]> wrote:
>> Kenny Riddile wrote:
>>> I'm still pretty inexperienced with the iostreams library, so this may be
>>> a simple question. I'm trying to use GIL to write a PNG to a memory stream
>>> instead of a file stream. The write_view() function in the new version of
>>> GIL's io extension expects an ostream opened in binary mode as it's first
>>> parameter, such as:
>>>
>>> using namespace std;
>>> using namespace boost::gil;
>>>
>>> ofstream outputStream( "foo.png", ios::out | ios::binary );
>>> write_view( outputStream, const_view(image), png_tag() );
>>>
>>> I'm attempting to write to memory instead of a file, by doing this:
>>>
>>> using namespace boost::gil;
>>> using namespace boost::iostreams;
>>>
>>> typedef stream< back_insert_device< std::vector<char> > > BufferStream;
>>>
>>> std::vector<char> buffer;
>>> BufferStream bufferStream( buffer );
>>>
>>> write_view( bufferStream, const_view(image), png_tag() );
>>>
>>> The data that ends up in buffer is identical to the data that ends up in
>>> foo.png from the first example if I don't open outputStream in binary mode.
>>> So how can I make a binary memory stream with the iostreams library? Do I
>>> need to write my own filter?
>>>
>>> _______________________________________________
>>> Unsubscribe & other changes:
>>> http://listarchives.boost.org/mailman/listinfo.cgi/boost
>>>
>> Ok, so redefining bufferStream like so works:
>>
>> std::stringstream bufferStream( std::ios_base::in | std::ios_base::out |
>> std::ios_base::binary );
>>
>> but it just feels "weird". Is there any cleaner way to do this with the
>> iostreams library?
>>
>
> This doesn't look weird to me.
> This is how I would do it.

Obviously I can use a typedef to hide the fact that it's a stringstream,
but the weird part for me is accessing the data via:

bufferStream.string().c_str()

Of course, that can be abstracted too. I was just wondering if the
iostreams library already offered some simple, elegant way of creating a
binary memory stream before I reinvent the wheel.

>
> You should probably post this to the boost-users list.

Honestly, I usually get better and more prompt responses when posting
here than on the users list...I just go where the answers are.