BSTR to std::string (std::wstring) and vice versa
BSTR
to std::wstring
:
// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));
std::wstring
to BSTR
:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
Doc refs:
std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
std::basic_string<>::empty() const
std::basic_string<>::data() const
std::basic_string<>::size() const
SysStringLen()
SysAllocStringLen()
You could also do this
#include <comdef.h>
BSTR bs = SysAllocString("Hello");
std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free
or std::string if you prefer
EDIT: if your original string contains multiple embedded \0 this approach will not work.