(1) 宽字符并不一定是Unicode,Unicode只是宽字符编码的一种实现。
(2) C语言对字符串的支持
为了仅维护一份源代码,而是用宏定义切换到Unicode或非Unicode,可以使用微软提供TCHAR.h,这是微软对C库的扩展,一般的规则是以_t开头。
单字符(char) : strlen printf
双字符(wchar_t): wcslen wprintf
通用 (TCHAR) _tcslen _tprintf
#ifdef _UNICODE
#define _T(x) L ## x
#else
#define _T(x) x
例如
wchar_t c = 'A' 没有必要加L
wchar_t *p = L"Hello!" 字符串常量前面加L,表示宽字符
TCHAR* p = _T("Hello!")
(3) windows对宽字符的支持
#ifdef _UNICODE
#define TEXT(x) L ## x
#else
#define TEXT(x) x
General TCHAR PTCHAR Ascii CHAR(char) PCHAR Unicode WCHAR(wchar_t) PWCHAR
lstrlen lstrcpy lstrcpyn lstrcat lstrcmp lstrcmpi
(4) windows下可以使用的字符串格式化函数
ascii unicode general C语言标准格式化输出 sprintf swprintf _stprintf C语言可变参数格式化输出 vsprintf vswprintf _vstprintf C语言(微软扩展)带长度格式化输出 _snprintf _snwprintf _sntprintf Windows标准格式化输出 wsprintfA wsprintfW wsprintf Windows可变参数格式化输出 wvsprintfA wvsprintfW wvsprintf
#include <windows.h> #include <tchar.h> #include <stdio.h> int CDECL MessageBoxPrintf (TCHAR * szCaption, TCHAR * szFormat, ...) { TCHAR szBuffer [1024] ; va_list pArgList ; // The va_start macro (defined in STDARG.H) is usually equivalent to: // pArgList = (char *) &szFormat + sizeof (szFormat) ; va_start (pArgList, szFormat) ; // The last argument to wvsprintf points to the arguments _vsntprintf (szBuffer, sizeof (szBuffer) / sizeof (TCHAR), szFormat, pArgList) ; // The va_end macro just zeroes out pArgList for no good reason va_end (pArgList) ; return MessageBox (NULL, szBuffer, szCaption, 0) ; } int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { int cxScreen, cyScreen ; cxScreen = GetSystemMetrics (SM_CXSCREEN) ; cyScreen = GetSystemMetrics (SM_CYSCREEN) ; MessageBoxPrintf (TEXT ("ScrnSize"), TEXT ("The screen is %i pixels wide by %i pixels high."), cxScreen, cyScreen) ; return 0 ; }
相当于
int CDECL MessageBoxPrintf (TCHAR * szCaption, TCHAR * szFormat, ...) { TCHAR szBuffer [1024] ; _vsntprintf (szBuffer, sizeof (szBuffer) / sizeof (TCHAR), szFormat, (char*)&szFormat + _INTSIZEOF(szFormat)) ; return MessageBox (NULL, szBuffer, szCaption, 0) ; }