一、TCHAR 、CString 、LPCTSTR转换
TCHAR tc[MAX_PATH] = { 0 };
wcout <<"TCHAR 转换成LPCTSTR类型=="<< (LPCTSTR)tc<<endl;
CString cs= tc;
wcout <<"TCHAR 转换成CString类型=="<< cs<<endl;
二、CString转换成char*
前面的法1、法2、法3当打印时可能只获取到首字母,因为版本改变了。这是法4能完美解决,建议用法4的方法。
CString strSource;//CString
char* charSource; //char*
法1:
charSource = (char*)strSource.GetBuffer(0);
法2:
charSource = (char*)strSource.GetBuffer(strSource.GetLength());
法3:
charSource = (char*)(LPCTSTR)strSource;
法4:
char *buf = ConvertLPWSTRToLPSTR(strSource.GetBuffer());
char* ConvertLPWSTRToLPSTR(LPWSTR lpwszStrIn)
{
LPSTR pszOut = NULL;
try
{
if (lpwszStrIn != NULL)
{
int nInputStrLen = wcslen(lpwszStrIn);
// Double NULL Termination
int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
pszOut = new char[nOutputStrLen];
if (pszOut)
{
memset(pszOut, 0x00, nOutputStrLen);
WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
}
}
} catch (std::exception e) {}
return pszOut;
}
三、char [] 和char*和wchar_t*和LPWSTR之间转换
法1:
#include <atlconv.h>
USES_CONVERSION;
char sz[] = "我是多字节string";
wchar_t *pWChar = A2W(sz);
LPWSTR lp = pWChar ;
char* buffer="123";
LPWSTR str=A2W(buffer);
LPCWSTR c_st=A2W(buffer);
wchar_t wsz[] = L"我是宽字符string";
char *pChar = W2A(wsz);
法2:
string str1 = "你好,我是w";
LPWSTR lp = ConvertCharToLPWSTR(str1.c_str());
LPWSTR ConvertCharToLPWSTR(const char * szString)
{
int dwLen = strlen(szString) + 1;
int nwLen = MultiByteToWideChar(CP_ACP, 0, szString, dwLen, NULL, 0);//算出合适的长度
LPWSTR lpszPath = new WCHAR[dwLen];
MultiByteToWideChar(CP_ACP, 0, szString, dwLen, lpszPath, nwLen);
return lpszPath;
}
四、std::string 转LPCSTR
LPCTSTR不是一个类型,而是两种类型:LPCSTR和LPCWSTR其中之一。会根据你当前程序是否使用UNICODE字符集来变成那二者之一。如果使用UNICODE字符集,则LPCTSTR = LPCWSTR,否则LPCTSTR = LPCSTR。
标准库的std::string转换成LPCSTR很简单:直接调用c_str()即可。例:
std::string a="abc";
LPCSTR str = a.c_str();
标准库还有一个wstring,代表宽字符的string,std::wstring转换成LPCWSTR也一样很简单:
std::wstring a = L"abc";
LPCWSTR str = a.c_str();
如果要是std::string转换成LPCWSTR或者std::wstring转换成LPCSTR那就比较麻烦了,需要调用MultiByteToWideChar或WideCharToMultiByte进行字符集之间的转换。不过大多数时候不需要这种交叉转换,一个程序一般只会使用一种字符集。