简体   繁体   中英

Converting large strings from BSTR tp std::string?

I have string in BSTR, and I would like to convert it using W2CA (WideCharToMultiByte):

USES_CONVERSION;
std::string myMBS = W2CA(myBSTR); // myBSTR is BSTR

But when string is extremely large - it throws exception "StackOverFlowException" on this line.

But when I use this:

std::wstring myWide(myBSTR);
std::string myMBS(myWide.begin(), myWide.end());

I works fine. Could anyone help with this behavior?

UPDATE : With large string I mean string about 10MB.

Look at the actual definition of W2CA from atlconv.h :

#define W2CA(lpw) ((LPCSTR)W2A(lpw))

Now look at the definition of W2A :

#define W2A(lpw) (\
    ((_lpw = lpw) == NULL) ? NULL : (\
            (_convert = (lstrlenW(_lpw)+1), \
            (_convert>INT_MAX/2) ? NULL : \
            ATLW2AHELPER((LPSTR) alloca(_convert*sizeof(WCHAR)), _lpw,
                         _convert*sizeof(WCHAR), _acp))))

It calls alloca , which allocates memory on the stack. So naturally if the string is very long, you risk exhausting the available stack space.

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