C++ 如何将nsACString转换为LPCWSTR?
我正在做一个firefox扩展(nsACString来自mozilla),但LoadLibrary需要一个LPCWSTR。我在谷歌上搜索了一些选项,但没有任何效果。有点超出我对字符串的理解,因此任何引用都将不胜感激。首先注意:C++ 如何将nsACString转换为LPCWSTR?,c++,string,firefox,C++,String,Firefox,我正在做一个firefox扩展(nsACString来自mozilla),但LoadLibrary需要一个LPCWSTR。我在谷歌上搜索了一些选项,但没有任何效果。有点超出我对字符串的理解,因此任何引用都将不胜感激。首先注意:LoadLibrary不需要接受LPWSTR。只有LoadLibraryW可以。您可以直接调用LoadLibraryA(通过一个狭窄的LPCSTR),它将为您执行翻译 如果你选择自己做,下面是一个可能的例子 nsACString sFoo = ...; // Some s
LoadLibrary
不需要接受LPWSTR
。只有LoadLibraryW
可以。您可以直接调用LoadLibraryA
(通过一个狭窄的LPCSTR
),它将为您执行翻译
如果你选择自己做,下面是一个可能的例子
nsACString sFoo = ...; // Some string.
size_t len = sFoo.Length() + 1;
WCHAR *swFoo = new WCHAR[len];
MultiByteToWideChar(CP_ACP, 0, sFoo.BeginReading(), len - 1, swFoo, len);
swFoo[len - 1] = 0; // Null-terminate it.
...
delete [] swFoo;
nsACString a
常量字符*pData;
PRUint32 iLen=NS_CStringGetData(a和pData) 这取决于nsACString(我称之为
str
)是否包含ASCII或UTF-8数据:
ASCII码
这是因为从UTF-8到WCHAR的转换所产生的字符数永远不会超过输入的字节数。使用std::vector而不是手动管理缓冲区生存期会更好。你的意思是保留空间并将&vec[0]传递给MultiByteToWideChar?@Alex:好吧,标准reserve()是不够的。您必须实际设置向量的大小:
std::vector vecFoo(len)代码>。然后vecFoo[0]
vecFoo[len-1]
是连续存储。
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];
// 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;