我试图从FormatMessage方法获取错误消息,但该方法始终返回false并且lpBuffer为null。
我想知道我做错了什么?
Thx
LPTSTR lpBuffer = NULL;
DWORD dwError = GetLastError();
int nResult = 0;
if (dwError >= 12000 && dwError <= 12174)
{
logger.info("dwError >= 12000 && dwError <= 12174");
nResult = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle("wininet.dll"), dwError, 0, lpBuffer, 0, NULL);
}
else
{
logger.info("in else");
nResult = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),lpBuffer, 0, NULL);
}
if (nResult)
{
logger.critical("Cannot start Drools client [" + m_exe + "] because [" + lpBuffer + "]");
//wcout << (LPWSTR)lpBuffer << endl;
LocalFree(lpBuffer);
}
else
{
logger.critical("Cannot start Drools client [" + m_exe + "] because [ Windows error code : " + boost::lexical_cast<string>(dwError) + " ]");
}
答案 0 :(得分:3)
你说错了。如果你传递FORMAT_MESSAGE_ALLOCATE_BUFFER
,你必须给它存储缓冲区的位置,所以“你必须将指针强制转换为LPTSTR(例如,(LPTSTR)&lpBuffer
)。”
I.e:
nResult = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle("wininet.dll"),
dwError,
0,
(LPTSTR)&lpBuffer,
BUFFER_SIZE,
NULL
);
请参阅此处的文档:
答案 1 :(得分:0)
您必须将&lpBuffer
传递给FormatMessage
,而不是lpBuffer
。