BSTR 到 std::string (std::wstring),反之亦然

2022-01-14 00:00:00 string com c++

在 C++ 中使用 COM 时,字符串通常是 BSTR 数据类型.有人可以使用 BSTR 包装器,例如 CComBSTR 或 MS 的 CString.但是因为我不能在 MinGW 编译器中使用 ATL 或 MFC,是否有标准代码片段将 BSTR 转换为 std::string (或 std::wstring) 反之亦然?

While working with COM in C++ the strings are usually of BSTR data type. Someone can use BSTR wrapper like CComBSTR or MS's CString. But because I can't use ATL or MFC in MinGW compiler, is there standard code snippet to convert BSTR to std::string (or std::wstring) and vice versa?

BSTR 是否还有一些类似于 CComBSTR 的非 MS 包装器?

Are there also some non-MS wrappers for BSTR similar to CComBSTR?

感谢所有以任何方式帮助我的人!正因为没有人解决 BSTRstd::string 之间的转换问题,我想在这里提供一些关于如何做到这一点的线索.

Thanks to everyone who helped me out in any way! Just because no one has addressed the issue on conversion between BSTR and std::string, I would like to provide here some clues on how to do it.

以下是我用来将 BSTR 转换为 std::stringstd::string 转换为 BSTR分别:

Below are the functions I use to convert BSTR to std::string and std::string to BSTR respectively:

std::string ConvertBSTRToMBS(BSTR bstr)
{
    int wslen = ::SysStringLen(bstr);
    return ConvertWCSToMBS((wchar_t*)bstr, wslen);
}

std::string ConvertWCSToMBS(const wchar_t* pstr, long wslen)
{
    int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);

    std::string dblstr(len, '');
    len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */,
                                pstr, wslen /* not necessary NULL-terminated */,
                                &dblstr[0], len,
                                NULL, NULL /* no default char */);

    return dblstr;
}

BSTR ConvertMBSToBSTR(const std::string& str)
{
    int wslen = ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
                                      str.data(), str.length(),
                                      NULL, 0);

    BSTR wsdata = ::SysAllocStringLen(NULL, wslen);
    ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
                          str.data(), str.length(),
                          wsdata, wslen);
    return wsdata;
}

推荐答案

BSTR to std::wstring:

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

 
std::wstringBSTR:

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

<小时>

文档参考:


Doc refs:

  1. std::basic_string::basic_string(constCharT*, size_type)
  2. std::basic_string<>::empty() const
  3. std::basic_string<>::data() 常量
  4. std::basic_string<>::size() const
  5. SysStringLen()
  6. SysAllocStringLen()

相关文章