BSTR to std::string (std::wstring) and vice versa(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
?
感谢所有以任何方式帮助我的人!正因为没有人解决 BSTR
和 std::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::string
和 std::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::wstring
到 BSTR
:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
<小时>
文档参考:
Doc refs:
std::basic_string
::basic_string(constCharT*, size_type) std::basic_string<>::empty() const
std::basic_string<>::data() 常量
std::basic_string<>::size() const
SysStringLen()
SysAllocStringLen()
这篇关于BSTR 到 std::string (std::wstring),反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:BSTR 到 std::string (std::wstring),反之亦然


- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01