wchar_t*和char*之间的互相转换的那些事

[cpp] view plaincopy
 
  1. 最近在看一写PE文件格式的东西,想做一个读取PE文件信息的小工具,中间遇到将LPVOID格式无法转换到LPTSTR格式,强制转换屡试屡败,多显示乱码。我们知道LPVOID格式可以直接转换到char *,最后发现一篇写char*与wchar_t*格式互相转换的文章,引用文中代码转换成功。  
  2. 原帖地址http://www.cnblogs.com/yyxr/archive/2009/10/06/1578458.html  
  3.   
  4. //将单字节char*转化为宽字节wchar_t*  
  5. wchar_t* AnsiToUnicode( const char* szStr )  
  6. {  
  7.     int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );  
  8.     if (nLen == 0)  
  9.     {  
  10.         return NULL;  
  11.     }  
  12.     wchar_t* pResult = new wchar_t[nLen];  
  13.     MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );  
  14.     return pResult;  
  15. }  
  16.   
  17. //将宽字节wchar_t*转化为单字节char*  
  18. inline char* UnicodeToAnsi( const wchar_t* szStr )  
  19. {  
  20.     int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );  
  21.     if (nLen == 0)  
  22.     {  
  23.         return NULL;  
  24.     }  
  25.     char* pResult = new char[nLen];  
  26.     WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );  
  27.     return pResult;  
  28. }  
原文地址:https://www.cnblogs.com/mfryf/p/3857990.html