这里有几个注意的,一定要保证空间足够。还有就是那个长度是单位字符个数,而不是字节数,在转换时,推荐被转换的字符串长度设置为-1,因为这样他会自动算出终结符结束。返回值也是转换的单位字符个数。例如”相等”有普通串转换为宽字节串,返回结果是3,(有终结符),而反过来就是5。如果返回时0 说明转换失败。
//mbstowcs()函数和wcstombs()函数,选自CRT库。平台无关,但需设定local。不设定Local,中文会乱码
bool UnicodeToAnsi(wchar_t* lpString,char* szAnsi)//(in,out)
{
size_t nLen=wcslen(lpString)*2,nReturnLen;//wcslen
char* lpszBuf=(char*)malloc(nLen);//malloc and
nReturnLen=wcstombs(szAnsi,lpString,nLen);//wcstombs
if(nReturnLen<0)
{
free(lpszBuf);
return false;
}
strcpy(szAnsi,lpszBuf);
return true;
}
bool UnicodeToAnsi(wchar_t* lpString,char* szAnsi)//(in,out)
{
char* pWideCharStr;
int nLenOfWideChar,nReturnlen;
nLenOfWideChar=WideCharToMultiByte(CP_ACP,0,lpString,-1,NULL,0,NULL,NULL);
//Header: Declared in Winnls.h; include Windows.h.
if(!nLenOfWideChar)
return false;
pWideCharStr=(char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,nLenOfWideChar+1);
nReturnlen=WideCharToMultiByte(CP_ACP,0,lpString,-1,pWideCharStr,nLenOfWideChar,NULL,NULL);
if(!nReturnlen)
{
HeapFree(GetProcessHeap(),0,pWideCharStr);
return false;
}
strcpy(szAnsi,pWideCharStr);
HeapFree(GetProcessHeap(),0,pWideCharStr);
return true;
}
bool AnsiToUnicode(char* lpString,wchar_t* szUnicode)//(in,out)
{
wchar_t* pWideCharStr;
int nLenOfWideChar,nReturnlen;
nLenOfWideChar=MultiByteToWideChar(CP_ACP,0,lpString,-1,NULL,0);
//Header: Declared in Winnls.h; include Windows.h.
if(!nLenOfWideChar)
return false;
pWideCharStr=(wchar_t*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,nLenOfWideChar*2);
nReturnlen=MultiByteToWideChar(CP_ACP,0,lpString,-1,pWideCharStr,nLenOfWideChar);
if(!nReturnlen)
{
HeapFree(GetProcessHeap(),0,pWideCharStr);
return false;
}
wcscpy(szUnicode,pWideCharStr);
HeapFree(GetProcessHeap(),0,pWideCharStr);
return true;
}