标签:
Convert CString to ANSI string in UNICODE projects
Quick Answer: use an intermediate CStringA.
Use intermediate CStringA (highly recommended):
CString LastNameW(L"Smith");
CStringA LastNameA(LastNameW);
FunctionForAnsi(LastNameA.GetString());
CString LastNameW(L"Smith");
FunctionForAnsi(CStringA(LastNameW).GetString());
Here are some other ways that either do not work or are not recommended. I list them here to document things to avoid. What not to do.
WideCharToMultiByte API function (not recommended):
CString LastNameW(L"Smith");
int nLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)LastNameW, -1, NULL, NULL);
LPSTR lpszA = new CHAR[nLen];
WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)LastNameW, -1, lpszA, nLen);
FunctionForAnsi(lpszA);
delete[] lpszA; // free the string
W2A ATL 3.0 macros (not recommended):
USES_CONVERSION;
CString LastNameW(L"Smith");
FunctionForAnsi(W2A(LastNameW.GetString()));
CW2A ATL 7.0 conversion template classes (not recommended):
CString LastNameW(L"Smith");
CW2A pszA(LastNameW.GetString()); // this is the right way
FunctionForAnsi(pszA);
CString LastNameW(L"Smith");
FunctionForAnsi(CW2A(LastNameW.GetString())); // improper usage, do not do this
CString LastNameW(L"Smith");
LPCSTR pszA = CW2A(LastNameW.GetString()); // improper usage, do not do this
FunctionForAnsi(pszA);
(LPCSTR)(LPCTSTR) cast:
CString LastName(L"Smith");
FunctionForAnsi((LPCSTR)(LPCTSTR)LastName); // improper usage, do not to this
REF:
ATL String: What‘s wrong with the USES_CONVERSION macros? How to avoid using them?
Using MFC MBCS/Unicode Conversion Macros
Convert CString to ANSI string in UNICODE projects
标签:
原文地址:http://www.cnblogs.com/time-is-life/p/5534481.html