Converting large strings from BSTR tp std::string?

452 views Asked by At

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.

1

There are 1 answers

3
jamesdlin On BEST ANSWER

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.