不能将convert std::string to LPWSTR放入函数中

MFC: Cannot put convert std::string to LPWSTR into a function

本文关键字:函数 LPWSTR string convert std 不能 to      更新时间:2023-10-16

我正在用Visual Studio 2015编写一个MFC项目,字符集配置为"使用Unicode字符集"

我需要从std::string转换到LPWSTR,以使用一些MFC对象属性,如LVITEM::pszTextCListCtrl, AfxMessageBox,…所以我使用这个来自internet的代码片段集:

String str = "Hello world!";
std::wstring wname(str.begin(), str.end());
LPWSTR lStr = const_cast<wchar_t*>(wname.c_str());
MessageBox(lStr);

这个方法工作得很好。但问题是,每次我需要转换,我必须重写这些语句,我把这个片段集到一个函数:

LPWSTR convertLPWSTR(std::string &str) {
    std::wstring wname(str.begin(), str.end());
    return const_cast<wchar_t*>(wname.c_str());
}
/...
String str = "Hello world!";
LPWSTR lStr = convertLPWSTR(str);
MessageBox(lStr);

但是消息框输出一个错误字符串(如错误字体)
:

有谁知道怎么解决这个问题吗?谢谢!

为什么不使用

CString str = _T("Hello world!") ;