why nResult != nConvertedLen,when use CComBSTR;
CComBSTR wsData = (char*)pvData;
when constuct CComBSTR,call A2WBSTR,but sometimes nResult != nConvertedLen,just 1/20. why?
inline BSTR A2WBSTR(_In_opt_ LPCSTR lp, int nLen = -1)
{
if (lp == NULL || nLen == 0)
return NULL;
USES_CONVERSION_EX;
BSTR str = NULL;
#pragma warning(push)
#pragma warning(disable: 6385)
int nConvertedLen = MultiByteToWideChar(_acp_ex, 0, lp,
nLen, NULL, NULL);
#pragma warning(pop)
int nAllocLen = nConvertedLen;
if (nLen == -1)
nAllocLen -= 1; // Don't开发者_JAVA百科 allocate terminating '\0'
str = ::SysAllocStringLen(NULL, nAllocLen);
if (str != NULL)
{
int nResult;
nResult = MultiByteToWideChar(_acp_ex, 0, lp, nLen, str, nConvertedLen);
ATLASSERT(nResult == nConvertedLen);
if(nResult != nConvertedLen)
{
SysFreeString(str);
return NULL;
}
}
return str;
}
My best guess is that there are multi-threading issues involved. As you can see both nResult
and nConvertedLen
are results to calls to MultiByteToWideChar
with the same source string. The first call is used to simply determine the length of the buffer that needs to be allocated to return the result of the conversion.
MultiByteToWideChar Documentation describes the behaviour of the function when the buffer length parameter is 0:
cchWideChar
[in] Size, in wide characters, of the buffer pointed to by the lpWideCharStr parameter.
If this value is zero, the function returns the required buffer size, in wide characters, and makes no use of the lpWideCharStr buffer.
So, the only time that the two values would be different is when string pointed to by lp
changes between to calls, most likely due to threading issues.
精彩评论