简体   繁体   中英

How to convert Bstr to Platform::String?

Now I am doing a Windows Metro App job, and I am developing a C++ component to get the input method's candidate List.

An issue occurs at the last step to output the result list. I can get each member of the candidate list, but the type is the "Bstr", to get them in the Metro App, I have to convert them into the type of "Platform::String".

How to convert Bstr to Platform::String?

I really appreciate any help you can provide.

The Platform::String constructor overloads make this very easy:

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

To be perfectly complete, both BSTR and a WinRT string can contain an embedded 0. If you want to handle that corner case then:

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

According to MSDN ( [1] , [2] ) we have this definitions:

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

So BSTR is of type wchar_t* or unsigned short* , or a null terminated 16-bit string.

From what I see from the documentation of Platform::String the constructor accepts a null-terminated 16-bit string as const char16*

While char16 is guaranteed represent UTF16, wchar is not.

UPDATE: As Cheers and hth. - Alf Cheers and hth. - Alf pointed out the line above isn't true for Windows/MSVC. I couldn't find any information on whether it is safe to cast between both types in this case. Since both wchar_t and char16_t are different integrated types I would still recommend to use std::codecvt to avoid problems.

So you should use std::codecvt to convert from wchar_t* to char16_t* and pass the result to the constructor of your Platform::String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM