While working with COM in C++ the strings are usually of BSTR
data type. Someone can use BSTR
wrapper like CComBSTR
or MS\'s CSt
Simply pass the BSTR directly to the wstring constructor, it is compatible with a wchar_t*:
BSTR btest = SysAllocString(L"Test");
assert(btest != NULL);
std::wstring wtest(btest);
assert(0 == wcscmp(wtest.c_str(), btest));
Converting BSTR to std::string requires a conversion to char* first. That's lossy since BSTR stores a utf-16 encoded Unicode string. Unless you want to encode in utf-8. You'll find helper methods to do this, as well as manipulate the resulting string, in the ICU library.
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.
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:
There is a c++ class called _bstr_t
. It has useful methods and a collection of overloaded operators.
For example, you can easily assign from a const wchar_t *
or a const char *
just doing _bstr_t bstr = L"My string";
Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();
. You can even convert it back to a regular char const char * c = bstr.operator char *();
You can then just use the const wchar_t *
or the const char *
to initialize a new std::wstring
oe std::string
.