【转】 Uniode TO ANSI 转换函数封装

===================================================================

// UNICODE 转换 ANSI 程序
int ustr_astr( CString unicodestr, char *ansistr )
{
int result = 0;
try
{
   int needlen = WideCharToMultiByte( CP_ACP, 0, unicodestr, -1, NULL, 0, NULL, NULL );
   if( needlen < 0 )
   {
    return needlen;
   }
   result = WideCharToMultiByte( CP_ACP, 0, unicodestr, -1, ansistr, needlen + 1, NULL, NULL );
   if( result < 0 )
   {
    return result;
   }
   return strlen( ansistr );
}
catch( ... )
{
}
return result;
}

使用方式

ustr_astr(csMsg,usef);

--------------------------------------------------------------------------------------------------------
// ANSI 转换 UNICODE 程序
int astr_ustr(char *ansistr ,WCHAR *unicodestr)
{
int result = 0;
try
{
   int needlen = MultiByteToWideChar( CP_ACP, 0, ansistr, -1, NULL, 0);
   if( needlen < 0 )
   {
    return needlen;
   }
   result = MultiByteToWideChar( CP_ACP, 0, ansistr, -1, unicodestr, needlen + 1);
   if( result < 0 )
   {
    return result;
   }
   return strlen(ansistr);
}
catch( ... )
{
}
return result;
}

使用方式

astr_ustr(csMsg,usef);

=================================================================

注意 以下 注释的 如果事先用 new char[XX];分配过内存的话 就不需要在使用了。

BOOL AnstrToUnstr (PSTR pMultiByteStr, PWSTR pWideCharStr) ;
BOOL AnstrToUnstr (PSTR pMultiByteStr, PWSTR pWideCharStr) {

   int nLenOfWideCharStr;   
   BOOL fOk = FALSE;   
   
   nLenOfWideCharStr = MultiByteToWideChar(CP_ACP, 0, pMultiByteStr, -1, NULL, 0);   
// pWideCharStr = (PWSTR)HeapAlloc(GetProcessHeap(), 0, nLenOfWideCharStr * sizeof(wchar_t));   
//if (pWideCharStr == NULL)   
//    return(fOk);   
   MultiByteToWideChar(CP_ACP, 0, pMultiByteStr, -1, pWideCharStr, nLenOfWideCharStr);   
   
// HeapFree(GetProcessHeap(), 0, pWideCharStr);   
   return(fOk);   
}

---------------------------------------------------------------------------------------------------

BOOL UnstrToAnstr (PWSTR pWideCharStr, PSTR pMultiByteStr) ;
BOOL UnstrToAnstr (PWSTR pWideCharStr, PSTR pMultiByteStr) {

   int nLenOfMultiByteStr; 
   BOOL fOk = FALSE;   

   nLenOfMultiByteStr = WideCharToMultiByte(CP_ACP, 0, pWideCharStr, -1,pMultiByteStr, (int)strlen(pMultiByteStr), NULL, NULL);   
// pMultiByteStr = (PSTR)HeapAlloc(GetProcessHeap(), 0, nLenOfMultiByteStr * sizeof(char));
//    if (pMultiByteStr == NULL)   
//    return(fOk); 
    WideCharToMultiByte(CP_ACP, 0, pWideCharStr, -1,pMultiByteStr,nLenOfMultiByteStr, NULL, NULL);   
   
// HeapFree(GetProcessHeap(), 0, pMultiByteStr);   
   return(fOk);   
}

原文地址:https://www.cnblogs.com/Daywei/p/1940226.html