简体   繁体   中英

Conversion from _bstr_t to std::string

I am simply trying to convert _bstr_t into std::string..

I found a post on this issue ( LINK ), and did exactly as described, but it is raising exception..

This is what I did:

_bstr_t BString;
std::string STDString((char *) BString);

And I get this error:

0CxC00000005: Access violation reading location 0x00000000

Specifically, after looking at the call stack, error in iosfwd.h:

static size_t __CLRCALL_OR_CDECL length(const _Elem *_First)
    {   // find length of null-terminated string
    return (*_First == 0 ? 0
        : _CSTD strlen(_First));
    }


What is the right way to convert _bstr_t to std::string..?

Thanks

BString can hold a null value, wheras std::string cannot, so you'll have to account for this.

const char* buf = BString;
int bstrlen = BString.length();
std::string STDString( buf?buf:"", bstrlen);

Note that BString probably uses UTF16 internally, and so the char* overload will use the current locale to choose a byte encoding, probably CP-1252, resulting in some characters being unable to be converted properly.

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