Is it legal to cast a LPTSTR directly to a BSTR?
Based on my understanding of BSTR, casting a LPTSTR to a BSTR directly will leave you with a corrupted length prefix. The example code explicitly states that a string literal cannot be stored to a BSTR. Can anyone confirm for me that a LPTSTR/LPCTSTR cannot be cast directly to a BSTR without corrupting the length prefix?
EDIT:
My confusion is from seeing this used in a call to a COM object. It turns out that when compiling the COM dll, a .tli file is generated that creates an intermediate method. This method takes type _bstr_t
. The _bstr_t
can take LPTSTR
in its constructor, so everything works smoothly.
A LPTSTR is a pointer to a char array (or TCHAR to be exact) BSTR is a structur (or composite data) consist of * Length prefix * Data string * Terminator
so casting will not work
You cannot cast, you must convert. You can use the built-in compiler intrinsic
_bstr_t
(fromcomutil.h
) to help you do this easily. Sample: