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

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