views:

99

answers:

3

I have programed an application on windows XP and in Visual Studio with c++ language.

In that app I used LoadResource() API to load a resource for giving a file in the resource memory.

It returned a pointer of memory block and I wanna cast the pointer to the std stream to use for compatibility.

Could anyone help me?

A: 

Most straightforward way is probably to convert the buffer to string and then stringstream:

std::stringstream ss(std::string(buf,len));

I think that will copy it twice, though, so if it turns out to be taking a lot of time you might need to look for alternatives. You could use strstream, but it might freak out the squares.

Steve Jessop
+1  A: 

Why would you need this?

Casting raw data pointers to streams means byte-by-byte copying of your resource and, therefore, lacks in performance (and, also to mention, I don't see any benefit in this approach).

If you want to work with raw memory, work with it. Casting here (compatibility?) seems to be a very strange approach.

Still, if you want to do it, you could create some stream from your memory block, that treats it as a sequence of bytes. In this case, it means using std::stringstream (istringstream).

After you lock your resource by LockResource, create a string from received void* pointer and pass it to your stringstream instance.

void* memory = LockResource(...);
// You would probably want to use SizeofResource() here
size_t memory_size = ... ;
std::string casted_memory(static_cast<char*>(memory), memory_size);
std::istringstream stream(casted_memory);
Kotti
+1  A: 

You can't cast the resource to a stream type. Either you copy the bytes:

std::stringstream ss;
ss.rdbuf().sputn(buf, len);

or you wrap your resource in your own streambuf:

class resourcebuf : public std::streambuf {
   // Todo: implement members including at least xsgetn, uflow and underflow
};

and pass it to istream::istream

MSalters
+1, like your approach very much
Kotti