开发者

How to cast a pointer of memory block to std stream

开发者 https://www.devze.com 2022-12-31 16:10 出处:网络
I have programed an application on windows XP and in Visual Studio with c++ language. In that app I used 开发者_Python百科LoadResource() API to load a resource for giving a file in the resource memo

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

In that app I used 开发者_Python百科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?


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


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消