Learning Hub Search Ctrl K

MFC › 8. Debugging and Maintenance

Unicode, 64-bit and Visual Studio Migration

TCHAR, _T and upgrading legacy MFC projects.

intermediate #mfc#unicode#tchar#utf-8#64-bit#migration#visual-studio-upgrade#int_ptr

Explanation

Old MFC code is often ANSI/MBCS and 32-bit. Most migration work is the same few topics.

Unicode

  • Windows is natively UTF-16 (wchar_t, 2 bytes per code unit). Build with UNICODE (Win32 API) and _UNICODE (CRT/MFC): both must be defined; Visual Studio sets them with Character Set: Use Unicode Character Set.
  • Write portable code with the TCHAR family: TCHAR, LPCTSTR, _T("text") (or TEXT("")), and the generic CRT names (_tcslen, _tcscpy_s, _stprintf_s, _ttoi). CString is CStringW in a Unicode build. Many projects now simply use wchar_t/L"" and W APIs directly.
  • MFC’s MBCS libraries are optional (a separate Visual Studio installer component) and deprecated. Compiling an MBCS project without them gives a warning/link error.
  • Convert at the boundary: files, networks and most other platforms use UTF-8. In MFC/ATL: CW2A(str, CP_UTF8) (UTF-16 → UTF-8), CA2W(bytes, CP_UTF8) (UTF-8 → UTF-16). Plain CT2A(str) uses the ANSI code page and loses characters outside it.
  • Text files need an encoding decision (UTF-8 with or without BOM, UTF-16 LE). CStdioFile text mode narrows to ANSI: avoid it for international text.
  • Resource files (.rc) should be saved as UTF-16 or have a code page pragma.

64-bit

  • int/long stay 32 bits on Win64 (LLP64); pointers and handles become 64 bits. Stuffing a pointer into an int, long, DWORD, or UINT truncates it.
  • Use pointer-sized types: INT_PTR, UINT_PTR, LONG_PTR, DWORD_PTR, SIZE_T, WPARAM, LPARAM.
  • SetWindowLong/GetWindowLong → SetWindowLongPtr/GetWindowLongPtr with GWLP_USERDATA, GWLP_WNDPROC.
  • Handlers changed: OnTimer(UINT_PTR), OnNcHitTest returns LRESULT, OnActivate, container sizes (GetSize() returns INT_PTR).
  • Fix warnings C4244/C4311/C4312/C4302 (conversion/truncation); they hint at real bugs.
  • Structures serialized to files with long/pointer members change size: use fixed-width types.

Upgrading Visual Studio

Retarget the platform toolset (v143), fix removed APIs and stricter language rules (/permissive-, nullptr, for scope), replace unsafe CRT functions (strcpy → strcpy_s, or define _CRT_SECURE_NO_WARNINGS temporarily), set WINVER/_WIN32_WINNT and rebuild with NOMINMAX if needed. Do one change at a time (Unicode, then 64-bit, then the new compiler).

Example

#include <afxwin.h>
#include <iostream>

int _tmain() {
    if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;

    // ---- Unicode: UTF-16 text and its UTF-8 bytes (\u escapes keep the source ASCII)
    CString text = L"Gr\u00fc\u00dfe";                       // 5 characters: G r u-umlaut sharp-s e
    CW2A utf8(text, CP_UTF8);                               // UTF-16 -> UTF-8
    CW2A ansi(text, CP_ACP);                                // UTF-16 -> the ANSI code page
    std::cout << "UTF-16 chars: " << text.GetLength()
              << ", UTF-8 bytes: " << strlen(utf8)
              << ", ANSI bytes: " << strlen(ansi) << "\n";

    CA2W back(utf8, CP_UTF8);                               // UTF-8 -> UTF-16
    std::cout << "round trip equal: " << (text == CString(back)) << "\n";

    // a character outside the ANSI code page is lost with CT2A / CP_ACP
    CString emoji = L"ok \u2713";                           // check mark
    CW2A lossy(emoji, CP_ACP);
    CW2A safe(emoji, CP_UTF8);
    std::cout << "ANSI: " << lossy << "  UTF-8 length: " << strlen(safe) << "\n";

    // ---- 64-bit: sizes of the types you must not mix
    std::cout << "sizeof(int)=" << sizeof(int) << " sizeof(long)=" << sizeof(long)
              << " sizeof(void*)=" << sizeof(void*) << " sizeof(LONG_PTR)=" << sizeof(LONG_PTR)
              << " sizeof(WPARAM)=" << sizeof(WPARAM) << "\n";

    void* p = &text;
    DWORD_PTR asNumber = reinterpret_cast<DWORD_PTR>(p);    // pointer-sized: safe
    // DWORD bad = (DWORD)p;                                 // truncates on x64: warning C4311/C4302
    std::cout << "pointer survives round trip: " << (reinterpret_cast<void*>(asNumber) == p) << "\n";
    return 0;
}

Common pitfalls

  • Defining only _UNICODE (or only UNICODE) gives a mix: some APIs take wide strings and others narrow.
  • Passing a char* where a wchar_t* is expected (or sizeof(buffer) where a character count is needed): sizeof(TCHAR buf[100]) is 200 bytes but 100 characters. Use _countof(buf).
  • CT2A/CW2A without a code page use ANSI: international text is silently turned into ?.
  • strlen/strcpy on a CString buffer in Unicode builds: use _tcslen, CString::GetLength().
  • Storing a HWND/pointer in an int or LONG: crashes on 64-bit only, often much later.
  • Assuming sizeof(long) == sizeof(void*). That’s true on 32-bit Windows and Linux 64-bit, but not on Win64.
  • Changing to Unicode without also changing file formats: a program that wrote ANSI .ini/.txt files then reads them as UTF-16 shows garbage.

Legacy vs modern

The TCHAR abstraction existed to compile one code base as both ANSI (Windows 9x) and Unicode (NT). Windows 9x is long gone, so modern code targets Unicode only: wchar_t, std::wstring, W APIs, and UTF-8 at the edges (/utf-8 compiler switch, the UTF-8 active code page manifest option in Windows 10 1903+). See CString and Collection Classes and Using Modern C++ in MFC Projects.

Exercises

1. Why is int len = sizeof(buf); a bug for TCHAR buf[64] in a Unicode build when passed to GetWindowText(buf, len)?

sizeof(buf) is 128 bytes, but the API expects the buffer size in characters (64). The API may write past the end. Use _countof(buf).