2010-09-28 138 views
2

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

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

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

-1,因为你不应该首先引入不必要的'char []'。 – MSalters 2010-09-28 12:02:57

回答

4

如果您的输入是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); 
} 

有关此Windows区域使用情况的更多详细信息,请参阅here。在这方面很容易搞乱Win32 API的使用 - 使用BSTR包装器来避免数据复制(如果明智地使用)和代码复杂性。

+0

这是更好的答案 - 通过char []转换**不是**无损。 – MSalters 2010-09-28 12:00:59

+0

请问wstring是否照顾null BSTR? – sharptooth 2010-09-28 13:10:34

+0

我的经验是,将NULL传递给'string'会导致访问冲突,我期望和'wstring'一样。我会在构造_bstr_t并正确处理之前检查它。编辑代码以显示此警卫。 – 2010-09-28 13:18:47

3

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

+1

哦,我不知何故错过了'visual-C++'标签。在Windows上,这是要走的路。 '+ 1'。 – sbi 2010-09-28 08:12:22

+1

+1,但要注意空BSTR - 它们对应于空字符串,并且可能导致未知程序崩溃。 – sharptooth 2010-09-28 13:09:53