Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you cast a LPTSTR to a BSTR?

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.

like image 746
Mashmagar Avatar asked Mar 10 '11 14:03

Mashmagar


1 Answers

If your program is unicode and your LPTSTR therefore is a LPWSTR, you can use SysAllocString to convert from a pointer to a wide character string to BSTR.

A direct cast is not possible because the two have different memory representations.

If you use C++, you can use the _bstr_t class to simplify the usage of BSTR strings.

like image 83
Timbo Avatar answered Sep 26 '22 08:09

Timbo