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

BSTR to std::string (std::wstring) and vice versa(BSTR 到 std::string (std::wstring),反之亦然)

本文介绍了BSTR 到 std::string (std::wstring),反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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()

这篇关于BSTR 到 std::string (std::wstring),反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:BSTR 到 std::string (std::wstring),反之亦然

基础教程推荐