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

后端 未结 4 399
迷失自我
迷失自我 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.

    0 讨论(0)
  • 2020-12-02 09:21

    You could also do this

    #include <comdef.h>
    
    BSTR bs = SysAllocString("Hello");
    std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free
    

    or std::string if you prefer

    EDIT: if your original string contains multiple embedded \0 this approach will not work.

    0 讨论(0)
  • 2020-12-02 09:25

    BSTR to std::wstring:

    // given BSTR bs
    assert(bs != nullptr);
    std::wstring ws(bs, SysStringLen(bs));
    

     
    std::wstring to BSTR:

    // given std::wstring ws
    assert(!ws.empty());
    BSTR bs = SysAllocStringLen(ws.data(), ws.size());
    

    Doc refs:

    1. std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
    2. std::basic_string<>::empty() const
    3. std::basic_string<>::data() const
    4. std::basic_string<>::size() const
    5. SysStringLen()
    6. SysAllocStringLen()
    0 讨论(0)
  • 2020-12-02 09:25

    There is a c++ class called _bstr_t. It has useful methods and a collection of overloaded operators.

    For example, you can easily assign from a const wchar_t * or a const char * just doing _bstr_t bstr = L"My string"; Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();. You can even convert it back to a regular char const char * c = bstr.operator char *(); You can then just use the const wchar_t * or the const char * to initialize a new std::wstring oe std::string.

    0 讨论(0)
提交回复
热议问题