BSTR to std::string (std::wstring) and vice versa

后端 未结 4 410
迷失自我
迷失自我 2020-12-02 09:01

While working with COM in C++ the strings are usually of BSTR data type. Someone can use BSTR wrapper like CComBSTR or MS\'s CSt

4条回答
  •  自闭症患者
    2020-12-02 09:06

    Simply pass the BSTR directly to the wstring constructor, it is compatible with a wchar_t*:

    BSTR btest = SysAllocString(L"Test");
    assert(btest != NULL);
    std::wstring wtest(btest);
    assert(0 == wcscmp(wtest.c_str(), btest));
    

    Converting BSTR to std::string requires a conversion to char* first. That's lossy since BSTR stores a utf-16 encoded Unicode string. Unless you want to encode in utf-8. You'll find helper methods to do this, as well as manipulate the resulting string, in the ICU library.

提交回复
热议问题