GetLastError() in std::string for windows phone

Windows dev always familiar with most Favorited GetLastError() function, and it has common wrapper to get error message in std::string. However most wrapper include FORMAT_MESSAGE_ALLOCATE_BUFFER which is not supported in windows phone or winrt application.

So you can use this function :

// Create a string with last error message
std::string GetLastErrorStdStr()
{
 DWORD error = GetLastError();
 if (error)
 {
 LPVOID lpMsgBuf;
 DWORD bufLen = FormatMessage(
 FORMAT_MESSAGE_FROM_SYSTEM |
 FORMAT_MESSAGE_IGNORE_INSERTS,
 NULL,
 error,
 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
 (LPTSTR) &lpMsgBuf,
 0, NULL );
 if (bufLen)
 {
 LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf;
 std::string result(lpMsgStr, lpMsgStr+bufLen);
 
 return result;
 }
 }
 return std::string();
}

Notice, without

FORMAT_MESSAGE_ALLOCATE_BUFFER
and
localfree to lpBuffer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s