How to convert BSTR to std::string in Visual Studio C++ 2010?

后端 未结 2 1889
迷失自我
迷失自我 2021-02-09 15:57

I am working on a COM dll. I wish to convert a BSTR to a std::string to pass to a method that takes a const reference parameter.

It seems that using _com_util::ConvertBS

相关标签:
2条回答
  • 2021-02-09 16:15

    Easy way

    BSTR => CStringW => CW2A => std::string.

    0 讨论(0)
  • You can do this yourself. I prefer to convert into the target std::string if possible. If not, use a temp-value override.

    // convert a BSTR to a std::string. 
    std::string& BstrToStdString(const BSTR bstr, std::string& dst, int cp = CP_UTF8)
    {
        if (!bstr)
        {
            // define NULL functionality. I just clear the target.
            dst.clear();
            return dst;
        }
    
        // request content length in single-chars through a terminating
        //  nullchar in the BSTR. note: BSTR's support imbedded nullchars,
        //  so this will only convert through the first nullchar.
        int res = WideCharToMultiByte(cp, 0, bstr, -1, NULL, 0, NULL, NULL);
        if (res > 0)
        {
            dst.resize(res);
            WideCharToMultiByte(cp, 0, bstr, -1, &dst[0], res, NULL, NULL);
        }
        else
        {    // no content. clear target
            dst.clear();
        }
        return dst;
    }
    
    // conversion with temp.
    std::string BstrToStdString(BSTR bstr, int cp = CP_UTF8)
    {
        std::string str;
        BstrToStdString(bstr, str, cp);
        return str;
    }
    

    Invoke as:

    BSTR bstr = SysAllocString(L"Test Data String")
    std::string str;
    
    // convert directly into str-allocated buffer.
    BstrToStdString(bstr, str);
    
    // or by-temp-val conversion
    std::string str2 = BstrToStdString(bstr);
    
    // release BSTR when finished
    SysFreeString(bstr);
    

    Something like that, anyway.

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