#include <windows.h>
#include <stdio.h>
//function: charTowchar
//purpose:char to WCHAR 、wchar_t、LPWSTR etc
void charTowchar(const char *chr, wchar_t *wchar, int size)
{
MultiByteToWideChar( CP_ACP, 0, chr,
strlen(chr)+1, wchar, size/sizeof(wchar[0]) );
}
//function: wcharTochar
//purpose:WCHAR 、wchar_t、LPWSTR to char
void wcharTochar(const wchar_t *wchar, char *chr, int length)
{
WideCharToMultiByte( CP_ACP, 0, wchar, -1,
chr, length, NULL, NULL );
}
int main (void)
{
char chr[128];
wchar_t *wchar = L"测试";
//wchar_t to char
wcharTochar(wchar, chr, sizeof(chr));
printf("char is %s\n", chr);
//char to wchar_t
wchar = (wchar_t *)malloc(sizeof(wchar_t) * 64);
charTowchar(chr, wchar, sizeof(wchar_t) * 64);
wprintf_s(L"%s\n", wchar);//
getchar();
return 0;
}
char:计算机编程语言(c、c++、java等)中可容纳单个字符的一种基本数据类型。
TCHAR:为了满足Unicode编码,对char的扩展,即_T(“str”)表示TCHAR类型
C++支持两种字符串,即常规的ANSI编码(使用""包裹)和Unicode编码(使用L""包裹),这样对应的就有了两套字符串字符串处理函数,比如:strlen和wcslen,分别用于处理两种字符串char和TCHAR类型
winnt.h头文件中:
typedef WCHAR TCHAR, *PTCHAR;
表明 TCHAR 与 WCHAR 属同一类型