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() conststd::basic_string<>::data() 常量std::basic_string<>::size() constSysStringLen()SysAllocStringLen()
这篇关于BSTR 到 std::string (std::wstring),反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:BSTR 到 std::string (std::wstring),反之亦然
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
