2
BSTR DoSOmething()
{
   return L"";
}

OR is it okay to pass TCHAR * to API taking BSTR as input parameter.

Is it okay to convert wchar_t string into BSTR via a return statement.Will it cause some memory corruption?

anand
  • 11,071
  • 28
  • 101
  • 159
  • Have a look at the Guide to BSTR and C String Conversions http://www.codeproject.com/Articles/4829/Guide-to-BSTR-and-C-String-Conversions. – Marius Bancila Sep 27 '12 at 10:46

1 Answers1

5

No, it is not OK because some APIs expect not just a WCHAR* pointer, which BSTR also is, but a real BSTR pointer with length information attached. Still casting this way might often work out well, and this might be misleading.

Everything about BSTRs: Eric's Complete Guide To BSTR Semantics.

A related quote from there:

2) A BSTR must be allocated and freed with the SysAlloc* family of functions. A PWSZ can be an automatic-storage buffer from the stack or allocated with malloc, new, LocalAlloc or any other memory allocator.

3) A BSTR is of fixed length. A PWSZ may be of any length, limited only by the amount of valid memory in its buffer.

4) A BSTR always points to the first valid character in the buffer. A PWSZ may be a pointer to the middle or end of a string buffer.

Roman R.
  • 68,205
  • 6
  • 94
  • 158