将 Win32 资源文件加载为 wstringstream [英] Loading Win32 resource file as wstringstream

查看:40
本文介绍了将 Win32 资源文件加载为 wstringstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对提出和回答的问题的跟进此处.我想使用一个文本文件作为资源,然后将它作为 stringstream 加载,以便我可以解析它.

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

但是,我不确定如何扩展它以使用 wstringstream 读取 unicode 文本文件.天真的方法产生不可读的字符:

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

由于 LPBYTE 只不过是一个 CHAR*,所以这不起作用也就不足为奇了,而是天真地将资源转换为 WCHAR* (LPWSTR) 也不起作用:

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

我猜这是因为 WCHAR 是 16 位,而不是像 CHAR 那样的 8 位,但我不确定如何解决这个问题.

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.

感谢您的帮助!

推荐答案

您的评论提供了关键的缺失细节.您编译为资源的文件被编码为 UTF-8.所以显而易见的选择是:

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. 使用问题中的代码,获取指向资源的指针,编码为 UTF-8,然后传递该 MultiByteToWideChar 以转换为 UTF-16.然后您可以将其放入 wstring.
  2. 在编译资源之前,将您编译为资源的文件转换为 UTF-16.然后您问题中的代码将起作用.
  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.

这篇关于将 Win32 资源文件加载为 wstringstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆