windows 将 BSTR 转换为 wstring

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3810730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:19:31  来源:igfitidea点击:

convert BSTR to wstring

windowsvisual-c++

提问by karikari

How to convert a char[256] to wstring?

如何将 char[256] 转换为 wstring?

update. here is my current code:

更新。这是我当前的代码:

char testDest[256];
char *p= _com_util::ConvertBSTRToString(url->bstrVal);

for (int i = 0; i <= strlen(p); i++)
{
  testDest[i] = p[i];   
}

// need to convert testDest to wstring to I can pass it to this below function...

writeToFile(testDestwstring);

回答by Steve Townsend

If your input is BSTR(as it seems to be) the data is already Unicode and you can just cast this directly to wstringas follows. _bstr_thas implicit conversions to both char*and wchar*which avoid the need for manual Win32 code conversion.

如果您的输入是BSTR(看起来是)数据已经是 Unicode,您可以直接将其转换wstring为如下所示。 _bstr_t具有对两者的隐式转换char*wchar*从而避免了手动 Win32 代码转换的需要。

if (url->bstrVal)
{
    // true => make a new copy - can avoid this if source 
    // no longer needed, by using false here and avoiding SysFreeString on source

    const _bstr_t wrapper(url->bstrVal, true); 
    std::wstring wstrVal((const _wchar_t*)wrapper);
}

See herefor more details on this area of Windows usage. It's easy to mess up the use of the Win32 API in this area - using the BSTR wrapper to do this avoids both data copy (if used judiciously) and code complexity.

有关Windows 使用方面的更多详细信息,请参见此处。在这方面很容易弄乱 Win32 API 的使用 - 使用 BSTR 包装器来做到这一点可以避免数据复制(如果使用得当)和代码复杂性。

回答by renick

MultiByteToWideCharwill return a UTF-16 string. You need to specify the source codepage.

MultiByteToWideChar将返回一个 UTF-16 字符串。您需要指定源代码页。