2010-09-28 171 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