这种错误,很多情况下是类型不匹配
LPTSTR表示为指向常量TCHAR
字符串的长指针
TCHAR
可以是wchar_t
或char,基于项目是多字节还是宽字节版本。
看下面的代码,代码来源:Example: Open a File for Reading
DisplayError(TEXT("CreateFile"));
void DisplayError(LPTSTR lpszFunction)
// Routine Description:
// Retrieve and output the system error message for the last-error code
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL );
lpDisplayBuf =
(LPVOID)LocalAlloc( LMEM_ZEROINIT,
( lstrlen((LPCTSTR)lpMsgBuf)
+ lstrlen((LPCTSTR)lpszFunction)
+ 40) // account for format string
* sizeof(TCHAR) );
if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error code %d as follows:\n%s"),
lpszFunction,
dw,
lpMsgBuf)))
{
printf("FATAL ERROR: Unable to output error code.\n");
}
_tprintf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
编译的时候,会出现标题中的错误,
错误处:
DisplayError(TEXT("CreateFile"));
并且在调试时,我们会发现出现????这样的错误,检查参数时会发现一堆奇怪的文字。
原因是在宽字节版本下,我们传入的是单个字节,而wchar_t*
指向它们的字符将期望每个字符都是2字节,所以就会出现????
我们可以这样简单的转换,宽字节版本:
DisplayError((LPTSTR)L"CreateFile");
多字节版本:
DisplayError((LPTSTR)"CreateFile");
但是我们最好要停止使用TCHAR类型,取而代之,使用mbstowcs()或MultiByteToWideChar()将char字符串转换为utf16。或始终使用wchar_t std :: wstring
多字节版本:
std::string str = "CreateFile";
const char* lp = str.c_str(); // or
LPCSTR lp = str.c_str();
宽字节版本:
std::wstring wstr = L"CreateFile";
const wchar_t* lp = wstr.c_str() // or
LPCWSTR lp = wstr.c_str();
另附mbstowcs的用法:
std::string str = "CreateFile"; //多字节
wchar_t wstr[11];
mbstowcs(wstr, str.c_str(), str.size()+1);
DisplayError(wstr); //宽字节版本