簡體   English   中英

如何將Bstr轉換為Platform :: String?

[英]How to convert Bstr to Platform::String?

現在,我正在執行Windows Metro App工作,並且正在開發C ++組件以獲取輸入法的候選列表。

在輸出結果列表的最后一步出現問題。 我可以獲取候選列表的每個成員,但是類型為“ Bstr”,要在Metro App中獲取它們,我必須將它們轉換為“ Platform :: String”的類型。

如何將Bstr轉換為Platform :: String?

我非常感謝您可以提供的任何幫助。

Platform :: String構造函數重載使此操作非常容易:

BSTR comstr = SysAllocString(L"Hello world");
auto wrtstr = ref new Platform::String(comstr);

為完全完善起見,BSTR和WinRT字符串都可以包含一個嵌入式0。如果要處理這種極端情況,則:

BSTR comstr = SysAllocStringLen(L"Hello\0world", 11);
auto wrtstr = ref new Platform::String(comstr, SysStringLen(comstr2));

根據MSDN( [1][2] ),我們有以下定義:

#if !defined(_NATIVE_WCHAR_T_DEFINED)
typedef unsigned short WCHAR;
#else
typedef wchar_t WCHAR;
#endif
typedef WCHAR OLECHAR;
typedef OLECHAR* BSTR; 

因此, BSTR的類型為wchar_t*unsigned short*或以null結尾的16位字符串。

根據我從Platform::String文檔中看到的內容,構造函數接受以NULL結尾的16位字符串作為const char16*

雖然char16被保證代表UTF16,但是wchar不是。

更新: Cheers and hth. - Alf Cheers and hth. - Alf指出上述行不適用於Windows / MSVC。 在這種情況下,我找不到有關在兩種類型之間進行轉換是否安全的任何信息。 由於wchar_tchar16_t都是不同的集成類型,因此我仍然建議使用std::codecvt以避免出現問題。

因此,您應該使用std::codecvtwchar_t*轉換為char16_t*並將結果傳遞給Platform::String的構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM