unicode和非unicode转换(char转wchar_t)

时间:2023-01-06 20:17:34
#include <windows.h>
#include <iostream>
#include <atlbase.h>
#include <comutil.h>
#include <atlstr.h>
using namespace std;

//方法1:MultiByteToWideChar, WideCharToMultiByte
void Way_1()
{
	char *p1 = "abc";
	wchar_t p2[20] = L"EFG";
	//char转wchar_t
	MultiByteToWideChar(CP_ACP, 0, p1, strlen(p1) + 1, p2, sizeof(p2));
	printf("%S\n", p2);
	//wchar_t转char
	wchar_t *p3= L"EFG";
	char p4[20];
	WideCharToMultiByte(CP_ACP, 0, p3, -1, p4, sizeof(p4), NULL, NULL);
	printf("%s\n", p4);
	
}

//方法2:A2W, W2A, T2A, A2T
void Way_2()
{//需要添加头文件 <atlbase.h>
	char * p1 = "abc";
	wchar_t *p2 = L"def";
	TCHAR *P3 = _T("CC");

	USES_CONVERSION;
	wchar_t *p5 = A2W(p1);

	char * p4 = T2A(P3);
}

//方法3:
void Way_3()
{//需要添加头文件<comutil.h>,一般在MFC工程下使用
	CString str = "abc";//只能存一种
	_bstr_t bstr = "abc";//可以用非unicode
	bstr += L"efg";//可以用unicode
	char *p = bstr;
	wchar_t *p2 = bstr;
}

int main()
{
	//Way_1();
	//Way_2();

	return 0;
}