Can you cast a LPTSTR to a BSTR?

2020-04-02 09:23发布

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.

8条回答
Anthone
2楼-- · 2020-04-02 10:22

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

查看更多
Emotional °昔
3楼-- · 2020-04-02 10:22

You cannot cast, you must convert. You can use the built-in compiler intrinsic _bstr_t (from comutil.h) to help you do this easily. Sample:

#include <Windows.h>
#include <comutil.h>

#pragma comment( lib, "comsuppwd.lib")

int main()
{
    LPTSTR p = "Hello, String";
    _bstr_t bt = p;
    BSTR bstr = bt;
    bstr;
}
查看更多
登录 后发表回答