There's a tried and tested answer here how to convert BSTR
-> std::wstring
. But I want to include the BSTR in a wstringstream
I am building up.
Clearly I can do (a bit contrived as a MRE):
std::wstring proc(BSTR bStr)
{
std::wstringstream ss;
std::wstring ws(bStr, SysStringLen(bStr));
ss << "The string is: " << ws;
return ss.str();
}
But is there a way to avoid creating the temporary ws
object and pipe bStr
in directly?
BSTR
is just a typedef forwchar_t*
as far as the compiler is concerned (it is just allocated differently at runtime than a normalwchar_t
C string).And by definition, a non-empty
BSTR
is always null-terminated (even though it is also length-prefixed).So, unless your string has embedded nul characters in it (which is possible), you can just use the normal
operator<<
for wide strings. Just watch out for the case where theBSTR
is a null pointer, which will exhibit undefined behavior for the operator.Try this: