string和wstring的互转

方式一:调用Windows API


   
   
  1. #include <Windows.h>
  2. //将string转换成wstring
  3. wstring string2wstring(string str)
  4. {
  5. wstring result;
  6. //获取缓冲区大小,并申请空间,缓冲区大小按字符计算
  7. int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
  8. TCHAR* buffer = new TCHAR[len + 1];
  9. //多字节编码转换成宽字节编码
  10. MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
  11. buffer[len] = '\0'; //添加字符串结尾
  12. //删除缓冲区并返回值
  13. result.append(buffer);
  14. delete[] buffer;
  15. return result;
  16. }
  17. //将wstring转换成string
  18. string wstring2string(wstring wstr)
  19. {
  20. string result;
  21. //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的
  22. int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
  23. char* buffer = new char[len + 1];
  24. //宽字节编码转换成多字节编码
  25. WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
  26. buffer[len] = '\0';
  27. //删除缓冲区并返回值
  28. result.append(buffer);
  29. delete[] buffer;
  30. return result;
  31. }

方式二:采用ATL封装_bstr_t的过渡


   
   
  1. #include <comutil.h>
  2. #pragma comment(lib, "comsuppw.lib")
  3. string ws2s(const wstring& ws)
  4. {
  5.      _bstr_t t = ws.c_str();
  6.      char* pchar = ( char*)t;
  7.      string result = pchar;
  8.      return result;
  9. }
  10. wstring s2ws(const string& s)
  11. {
  12.      _bstr_t t = s.c_str();
  13.      wchar_t* pwchar = ( wchar_t*)t;
  14.     wstring result = pwchar;
  15.      return result;
  16. }
发布了74 篇原创文章 · 获赞 23 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/shenshaoming/article/details/103138037
今日推荐