How to convert BSTR to LPCTSTR

Posted on May 31, 2009

I’ve had to deal with a pointer of a BSTR string returned to an event handler of an ActiveX control. I wanted to convert it to LPCTSTR, and a simple implicit type-casting worked seamlessly when I tried in a test project.

void put_UseServer(LPCTSTR newValue);

void ServerChanged(BSTR* NewServer)
{
	put_UseServer(*NewServer); // This conversion works only in Unicode Character Set
}

However, when I copied the same code into my actual project, it caused an error. The reason was that my project used the Multi-byte Character Set whereas I tested the code in the Unicode Character Set. The simplest solution I found which also works in the Multi-byte Character set is like the following.

void put_UseServer(LPCTSTR newValue);

void ServerChanged(BSTR* NewServer)
{
	put_UseServer(COLE2CT(*NewServer)); // Use ATL String Conversion Class
}

More information about ATL and MFC String Conversion is on the MSDN website.