简体   繁体   中英

Convert LPCOLESTR to BSTR?

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

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 BSTR s

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM