Convert CString to const char* in Unicode MFC Applications
Converting a CString from Unicode (TCHAR) to ASCII (const char*) is essential for interacting with legacy code or external libraries in Unicode MFC applications. Here's how you can achieve this:
Using CT2A Macro
The CT2A macro provides a convenient way to convert a Unicode CString to ASCII. It takes the CString as an argument and an optional second argument to specify the code page. By default, it uses the local code page.
<code class="cpp">// Convert using the local code page CString str(_T("Hello, world!")); CT2A ascii(str); TRACE(_T("ASCII: %S\n"), ascii.m_psz);</code>
Additional Use Cases
The CT2A macro can also be employed to convert a Unicode CString to UTF8 or any other Windows code page:
<code class="cpp">// Convert to UTF8 CString str(_T("Some Unicode goodness")); CT2A ascii(str, CP_UTF8); TRACE(_T("UTF8: %S\n"), ascii.m_psz); // Convert to Thai code page CString str(_T("Some Thai text")); CT2A ascii(str, 874); TRACE(_T("Thai: %S\n"), ascii.m_psz);</code>
CA2T Macro and Compatibility
There is also a complementary CA2T macro that converts from ASCII to Unicode. Both the CT2A and CA2T macros can be used in ATL/WTL applications with Visual Studio 2003 or later.
Additional Resources
For more in-depth information on these macros and code page conversion, refer to the Microsoft Developer Network (MSDN).
The above is the detailed content of How to Convert a CString to `const char*` in Unicode MFC Applications?. For more information, please follow other related articles on the PHP Chinese website!