c++ - 如何从 nsACString 转换为 LPCWSTR?

标签 c++ string firefox

我正在制作一个 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/

相关文章:

javascript - 删除滚动条 Firefox 桌面

java - Java和C++之间的套接字通信

c++ - C++中的数据库问题

c++ - 警告 : conversion from string literal to 'char *' is deprecated

c - 我不知道这段代码出了什么问题?

javascript - 如何使用 javascript 创建音频播放器?

javascript - Reporting Services - RSClientPrint.Print 不是函数

c++ - 为什么 std::swap 不使用交换习语?

c++ - 在构造函数中初始化成员时,是否应该在成员上使用 std::move?

java - 计数器文本文件中用户指定字符串的出现次数