unicode字符转换成ansi字符

来源:互联网 发布:阿里云oss下载文件 编辑:程序博客网 时间:2024/06/08 18:22

#include <atlconv.h>
USES_CONVERSION;
W2A  
用是把unicode字符转换成ansi字符。宽字节转换成多字节

(WideCharToMultiByte) 
A2W
用是把ansi字符转换成unicode字符。多字节转换成宽字节

(MultiByteToWideChar)
1. CString 转 wchar_t

CString path = "asdf";wchar_t wstr[256] =

path.AllocSysString();

或者:wchar_t wcstring[256];

MultiByteToWideChar(CP_ACP,0,wcstring,-1,path,256);

2. wchar_t转CString

WideCharToMultiByte(CP_ACP,0,path,256,wcstring,256,NULL,NULL);

CHAR为单字节字符。还有个WCHAR为Unicode字符,即不论中英文,每个字有两个字节组成。

如果当前编译方式为ANSI(默认)方式,TCHAR等价于CHAR,如果为Unicode方式,TCHAR等价于WCHAR。

LPCSTR 相当于CONST CHAR * 和LPSTR 相当于CHAR *。

Unicode称为宽字符型字串,COM里使用的都是Unicode字符串。
将ANSI转换到Unicode
(1)通过L这个宏来实现,例如: CLSIDFromProgID( L"MAPI.Folder",&clsid);
(2)通过MultiByteToWideChar函数实现转换,例如:
char *szProgID = "MAPI.Folder";
CLSID clsid;

int len = ::MultiByteToWideChar (CP_ACP, 0, szProgID, -1, 0, 0);
wchar_t *wstr = new wchar_t[len];
::MultiByteToWideChar (CP_ACP, 0,szProgID, -1, wstr, len);

(3)通过A2W宏来实现,例如:
USES_CONVERSION;
CLSIDFromProgID( A2W(szProgID),&clsid);
将Unicode转换到ANSI
(1)使用WideCharToMultiByte,例如:
// 假设已经有了一个Unicode 串 wszSomeString... 

int len = ::WideCharToMultiByte (CP_ACP, 0, wszSomeString, -1, 0, 0, 0, 0);
char *str = new char[len];
::WideCharToMultiByte (CP_ACP, 0, wszSomeString, -1, str, len, 0, 0);

(2)使用W2A宏来实现,例如:
USES_CONVERSION;
pTemp=W2A(wszSomeString);