When creating a BSTR
(using _bstr_t
as wrapper class) I have to use some of the constructors of _bstr_t
. Since a BSTR
is a length prefixed string that may contains null-characters, there must be a possiblity to create such a string using a native string without relying on the null-termination of the given native string.
To give an example:
wchar_t* pwNativeString = L"abc\0def\0\0ghi\0\0\0"; // + automatic "\0"
// Now I want to create a BSTR using _bstr_t by this string.
_bstr_t spBSTR = _bstr_t(pwNativeString);
The problem is that the constructor relies on the null-termination of pwNativeString
. So the resulting BSTR
is just "abc"
and nothing more. So my question is: How to create a BSTR
or _bstr_t
and deliver a pointer to an array with a specific length? In the following a pseudo-code example:
_bstr_t spBSTR = _bstr_t(pwNativeString, 15);
Use
SysAllocStringLen
to allocate theBSTR
, and then use the two-argument_bstr_t
constructor to create a_bstr_t
object from it. If you set the second parameter totrue
, then you'll need to callSysFreeString
afterward. Otherwise, the_bstr_t
object owns the string and will free it for you.