最近在学NeHe的Opengl教程,把源代码下了下来,在VC6.0中编译正常,可是拿到VS2005中就各种报错,其实就是一个问题,char*到LPCWSTR的转化问题,也就是ANSI和UNICODE的转换问题,对应那些非变量的字符串,用宏定义_T()就可以解决,比如MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);只要改成MessageBox(NULL,_T("Window Creation Error."),_T("ERROR"),MB_OK|MB_ICONEXCLAMATION);即可,可是悲催的发现有一个函数的形参也存在这种问题,而_T()是解决不了变量的转换的,然后就是各种网上找解放方案,在老外的一个网站上找到了根本解决方法:ANSI到UNICODE的转换:
char *ansistr = "Hello" int lenA = lstrlenA(ansistr); int lenW; BSTR unicodestr; lenW = ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, 0, 0); if (lenW > 0) { // Check whether conversion was successful unicodestr = ::SysAllocStringLen(0, lenW); ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, unicodestr, lenW); } else { // handle the error } // when done, free the BSTR ::SysFreeString(unicodestr);
UNICODE到ANSI的转换:BSTR unicodestr = 0; char *ansistr; SomeCOMFunction(&unicodestr); int lenW = ::SysStringLen(unicodestr); int lenA = ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, 0, 0, NULL, NULL); if (lenA > 0) { ansistr = new char[lenA + 1]; // allocate a final null terminator as well ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, ansistr, lenA, NULL, NULL); ansistr[lenA] = 0; // Set the null terminator yourself } else { // handle the error } //...use the strings, then free their memory: delete[] ansistr; ::SysFreeString(unicodestr);
BSTR unicodestr = 0; char *ansistr; SomeCOMFunction(&unicodestr); int lenW = ::SysStringLen(unicodestr); int lenA = ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, 0, 0, NULL, NULL); if (lenA > 0) { ansistr = new char[lenA + 1]; // allocate a final null terminator as well ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, ansistr, lenA, NULL, NULL); ansistr[lenA] = 0; // Set the null terminator yourself } else { // handle the error } //...use the strings, then free their memory: delete[] ansistr; ::SysFreeString(unicodestr);