我正在制作一个 firefox 扩展(nsACString 来自 mozilla),但 LoadLibrary 需要 LPCWSTR。我用谷歌搜索了一些选项,但没有任何效果。有点超出了我对字符串的了解,所以任何引用文献也将不胜感激。
最佳答案
这取决于您的 nsACString(我将其称为 str
)保存的是 ASCII 还是 UTF-8 数据:
ASCII
std::vector<WCHAR> wide(str.Length()+1);
std::copy(str.beginReading(), str.endReading(), wide.begin());
// I don't know whether nsACString has a terminating NUL, best to be sure
wide[str.Length()] = 0;
LPCWSTR newstr = &wide[0];
UTF-8
// get length, including nul terminator
int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
str.BeginReading(), str.Length(), 0, 0);
if (len == 0) panic(); // happens if input data is invalid UTF-8
// allocate enough space
std::vector<WCHAR> wide(len);
// convert string
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
str.BeginReading(), str.Length(), &wide[0], len)
LPCWSTR newstr = &wide[0];
这只会分配所需的空间 - 如果您想要更快的代码,可能会使用比所需更多的内存,您可以将前两行替换为:
int len = str.Length() + 1;
这是可行的,因为从 UTF-8 到 WCHAR 的转换永远不会产生比输入字节数更多的字符。
关于c++ - 如何从 nsACString 转换为 LPCWSTR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1900756/