QString与TCHAR/wchar_t/LPWSTR之间的类型转换

TCHAR/wchar_t/LPWSTR这三种类型在Unicode字符集中是一样的。
在Qt框架中,经常会使用到windows的函数,而自VC6.0以后,windows默认使用Unicode字符集,windows也相应的推出了TCHAR作为char的宽字符集和多字符集的通用类型来表示char类型。Unicode字符集中,TCHAR代表的是wchar_t,而Qt中,大多数情况下使用QString,这时就需要wchar_t*和QString之间的相互转换。代码如下:

1.TCHAR *类型转为QString类型:

 1 QString MainWindow::WcharToChar(const TCHAR *wp, size_t codePage)
 2 {
 3     QString str;
 4     int len = WideCharToMultiByte(codePage, 0, wp, wcslen(wp), NULL, 0, NULL, NULL);
 5     char *p = new char[len + 1];
 6     memset(p, 0, len + 1);
 7     WideCharToMultiByte(codePage, 0, wp, wcslen(wp), p, len, NULL, NULL);
 8     p[len] = '';
 9     str = QString(p);
10     delete p;
11     p = NULL;
12     return str;
13 }

2.QString类型转为TCHAR *类型:

 1 TCHAR *CharToWchar(const QString &str)
 2 {
 3     QByteArray ba = str.toUtf8();
 4     char *data = ba.data(); //以上两步不能直接简化为“char *data = str.toUtf8().data();”
 5     int charLen = strlen(data);
 6     int len = MultiByteToWideChar(CP_ACP, 0, data, charLen, NULL, 0);
 7     TCHAR *buf = new TCHAR[len + 1];
 8     MultiByteToWideChar(CP_ACP, 0, data, charLen, buf, len);
 9     buf[len] = '';
10     return buf;
11 }

这里需要注意一点,CharToWchar函数返回的是一个TCHAR 的指针,而且是在函数内申请了内存,所以当我们使用完结果后,应该delete此指针,如:
QString str("你好");
TCHAR *data = CharToWchar(str);
......
delete data;
data = NULL;

原出处:https://blog.csdn.net/lance710825/article/details/78330838,,已经过验证:环境Qt5.6.3 minGW。

原文地址:https://www.cnblogs.com/acmexyz/p/11648837.html