How can I set the length, when creating a BSTR (using _bstr_t wrapper) by a native string?

2.5k views Asked by At

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);
1

There are 1 answers

3
Rob Kennedy On BEST ANSWER

Use SysAllocStringLen to allocate the BSTR, and then use the two-argument _bstr_t constructor to create a _bstr_t object from it. If you set the second parameter to true, then you'll need to call SysFreeString afterward. Otherwise, the _bstr_t object owns the string and will free it for you.

BSTR bstrIn = SysAllocStringLen(L"abc\0def\0\0ghi\0\0\0", 15);
_bstr_t spBSTR(bstrIn, false);