tags:

views:

369

answers:

2

Any ideas on how to make a BSTR out of an LPCOLESTR? Silly thing to get hung up on..

+5  A: 

An LPCOLESTR is just a const wchar_t*, so you can use SysAllocString() to create a BSTR:

LPCOLESTR olestr = ...;
BSTR bstr = SysAllocString(olestr);

Be sure to call SysFreeString() when you're done with your BSTR. See also the MSDN documentation on BSTRs

Adam Rosenfield
Note that OLECHAR == wchar_t is true only on a Wintel platform. Not sure what the other platforms were, but it was funny stuff, and on them BSTR is probably just a char *, too, so your answer is correct for all practical purposes ;)
peterchen
A: 

The difference between BSTR and LPCOLESTR is that BSTR has the length of the string prefixed before the string, LPCOLESTR hasn't.

A BSTR doesn't necessarily have an ending \0 marking end of string, since the length of the string is prefixed, to convert I usually use the class CComBSTR (atlcomcli.h), the ctor takes either BSTR or LPCOLESTR as argument and there is a member BSTR() to get the BSTR representation:

CComBSTR b( yourolestring )
// b.BSTR()

CComBSTR will handle the allocating/freeing so no risk of memory leak.

Anders K.