简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM