mhjlam
mhjlam

Reputation: 160

Loading Win32 resource file as wstringstream

This a follow up of the question asked and answered here. I want to use a text file as a resource and then load it as a stringstream so that I can parse it.

The following code shows what I currently have:

std::string filename("resource.txt");
HRSRC hrsrc = FindResource(GetModuleHandle(NULL), filename.c_str(), RT_RCDATA);
HGLOBAL res = LoadResource(GetModuleHandle(NULL), hrsrc);
LPBYTE data = (LPBYTE)LockResource(res);
std::stringstream stream((LPSTR)data);

However, I am unsure of how to extend this to read a unicode text file using a wstringstream. The naive approach yields unreadable characters:

...
LPBYTE data = (LPBYTE)LockResource(res);
std::wstringstream wstream((LPWSTR)data);

Since LPBYTE is nothing more than a CHAR*, it is no surprise that this doesn't work, but naively converting the resource to a WCHAR* (LPWSTR) does not work either:

...
LPWSTR data = (LPWSTR)LockResource(res);
std::wstringstream wstream(data);

I am guessing this is because a WCHAR is 16-bit instead of 8-bit like a CHAR, but I'm not sure how to work around this.

Thanks for any help!

Upvotes: 1

Views: 1162

Answers (1)

David Heffernan
David Heffernan

Reputation: 612954

Your comment supplies the key missing detail. The file that you compiled into a resource is encoded as UTF-8. So the obvious options are:

  1. Using the code in your question, get a pointer to the resource, encoded as UTF-8, and pass that MultiByteToWideChar to convert to UTF-16. Which you can then put into a wstring.
  2. Convert the file that you compile into a resource to UTF-16, before you compile the resource. Then the code in your question will work.

Upvotes: 2

Related Questions