从 BSTR tp std::string 转换大字符串

Converting large strings from BSTR tp std::string?

本文关键字:转换 字符串 string tp std BSTR      更新时间:2023-10-16

我在BSTR中有字符串,我想使用W2CA(WideCharToMultiByte)转换它:

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

但是当字符串非常大时 - 它会在此行上抛出异常"StackOverFlowException"。

但是当我使用它时:

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

我工作正常。任何人都可以帮助这种行为吗?

更新:对于大字符串,我的意思是大约 10MB 的字符串。

atlconv.hW2CA的实际定义:

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

现在看看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))))

它调用 alloca ,在堆栈上分配内存。 因此,如果字符串很长,自然会有耗尽可用堆栈空间的风险。