[英]How to convert BSTR to std::string in Visual Studio C++ 2010?
[英]How would you convert a std::string to BSTR*?
你如何将std::string
转换为BSTR*
?
STDMETHODIMP CMyRESTApp::rest(BSTR data, BSTR* restr)
{
RESTClient restclient;
RESTClient::response resp = restclient.get(data);
Log("Response Status code: %s", resp.code);
Log("Response Body: %s", resp.body);
*restr = // here
return S_OK;
}
我需要转换resp.body
然后在这里返回*restr
。
基于ATL的方法是使用ATL::CComBSTR
,然后使用Detach()
(或CopyTo(...)
)将得到的CComBSTR
发送到BSTR*
就像是:
CComBSTR temp(stlstr.c_str());
*restr = temp.Detach();
另外一般来说,对于std::basic_string
您可以使用Win32 API Sys*
系列函数,例如SysAllocStringByteLen
和SysAllocString
;
// For the `const char*` data type (`LPCSTR`);
*restr = SysAllocStringByteLen(stlstr.c_str(), stlstr.size());
// More suitable for OLECHAR
*restr = SysAllocString(stlwstr.c_str());
OLECHAR
依赖于目标平台,但通常是wchar_t
。
鉴于您的代码 ,最短的代码片段可能就是;
*restr = SysAllocStringByteLen(resp.body.c_str(), resp.body.size());
请注意,这些Windows API函数使用“常规”Windows代码页转换,如果需要,请参阅MSDN文档,了解如何控制它。
std::string
由char
s生成; BSTR
通常是基于Unicode UTF-16 wchar_t
的字符串,具有长度前缀。
即使可以使用BSTR
作为编组字节数组的简单方法(因为BSTR
是长度前缀的,因此它可以存储嵌入的NUL),因此BSTR
也可能用于存储非UTF-16文本, BSTR
通常的“自然”行为是包含Unicode UTF-16 wchar_t
-string 。
所以,第一个问题是澄清std::string
使用什么样的编码 (例如:Unicode UTF-8?或其他一些代码页?)。 然后,您必须将该字符串转换为Unicode UTF-16,并创建包含该UTF-16字符串的BSTR
。
要从UTF-8(或其他代码页)转换为UTF-16,您可以使用MultiByteToWideChar()
函数 。 如果源std::string
包含UTF-8字符串,则可以将CP_UTF8
代码页值与上述API一起使用。
获得UTF-16转换后的字符串后,可以使用它创建BSTR
,并将其作为输出BSTR*
参数传递。
创建BSTR
的主要Win32 API是SysAllocString()
。 还有一些变体可以指定字符串长度。
或者,作为一种更方便的替代方法,您可以使用ATL的CComBSTR
类将BSTR
包装在安全的RAII边界中,并使用其Detach()
方法将BSTR
作为输出BSTR*
参数传递。
CComBSTR bstrResult( /* UTF-16 string from std::string */ );
*restr = bstrResult.Detach();
奖金阅读:
这很有可能:
std::string singer("happy new year 2016");
_bstr_t sa_1(singer.c_str()); //std::string to _bstr_t
_bstr_t sa_2("Goodbye 2015");
std::string kapa(sa_2); //_bstr_t to std::string
size_t sztBuffer = (resp.body.length() + 1) * sizeof(wchar_t);
wchar_t* pBuffer = new wchar_t[resp.body.length() + 1];
ZeroMemory(&pBuffer[0], sztBuffer);
MultiByteToWideChar(CP_ACP, 0, resp.body.c_str(), resp.body.length(), pBuffer, sString.length());
SysAllocString((OLECHAR*)pBuffer);
delete[] pBuffer;
不要忘记之后解除分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.