-
Deleting BSTR help!
Hi guys,
So is it legal to do the following to free the allocated string?
Code:
LPWSTR szString = SysAllocString("Some String");
...
SysFreeString((BSTR)(szString));
If I remember correctly, I think a BSTR string has its size recorded within it, so I wasn't sure casting WCHAR* to BSTR was valid or not.
Thanks!
-
The cast should not be needed. Does it generate a compile error without the cast?
-
No I haven't tried that yet. So LPWSTR string to BSTR string cast is okay when SysFreeString(), huh? Thanks!
-
SysAllocString returns a BSTR, which is entirely different from a wide character string. Attempting to cast between the two is not an option.
If you want a wide character string, then I think this will work:
Code:
LPWSTR szString = new WSTR[lstrlen(L"Some String") + sizeof(*szString))];
lstrcpy(szString, L"Some String");
-
>> Attempting to cast between the two is not an option.
It can be an option. If the BSTR is a NULL terminated string, you can treat it just like a "const wchar_t*" string.
gg
-
I may be wrong, but I thought that BSTR->WCHAR* cast is okay but WCHAR*->BSTR cast is not okay (since BSTR contains more info)? Isn't BSTR basically a WCHAR* string with the string size information prefixed? And how can ther be a BSTR string without the NULL terminator (I mean unless we intentially erase the terminator character)?
-
BSTR's don't *have* to be NULL terminated - since their length is prefixed.
Correct - If an API expects a BSTR then you must pass a BSTR. If an API takes a const WCHAR*, then you can pass in a NULL terminated BSTR. For non-const WCHAR* API's, you need make sure it doesn't do anything to the buffer that a BSTR wouldn't appreciate.
gg