【问题标题】:Cannot convert from 'TCHAR [260]' to 'std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>无法从 'TCHAR [260]' 转换为 'std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>
【发布时间】:2018-03-30 18:27:19
【问题描述】:

错误 C2440:“正在初始化”:无法从“TCHAR [260]”转换为 'std::basic_string,std::allocator>

我收到了这个错误,卡了几个小时..

TCHAR szModName[MAX_PATH];
if (!GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) // Get the full path to the module's file
    continue;

wstring modName = szModName; <-------- this is what im having problem with

【问题讨论】:

  • 至少你没有应用错误的 C 风格转换来消除错误,就像很多人似乎所做的那样(然后想知道为什么他们的程序崩溃或他们的字符串看起来很奇怪)。我对此表示赞赏。

标签: c++ char tchar


【解决方案1】:

TCHAR 定义为charwchar_t,具体取决于您是否定义了UNICODE 宏。在您的情况下,它看起来没有定义,因此您正在尝试从 char[] 数组构造 std::wstring

我建议您始终在 Windows 上使用广泛的 API,因为这是获得适当 Unicode 支持的唯一方法:

wchar_t szModName[MAX_PATH];
if (!GetModuleFileNameExW(hProcess, hMods[i], szModName, MAX_PATH))
    continue;

wstring modName = szModName;

GetModuleFileNameEx 不是一个函数,而是一个宏,可以根据UNICODE 宏扩展为GetModuleFileNameExAGetModuleFileNameExW

最初,提供TCHAR 变体是为了便于从不支持Unicode 的旧Windows 版本过渡到支持Unicode 的新的基于NT 的Windows 版本。如今,根本没有理由使用 ANSI 变体。

【讨论】:

  • 或者,您可以取消临时缓冲区并直接将文件名接收到std::wstring,例如:wstring modName(MAX_PATH, 0); DWORD len = GetModuleFileNameExW(hProcess, hMods[i], &amp;modName[0] /* or: modName.data() */, MAX_PATH); if (!len) continue; modName.resize(len);
  • @RemyLebeau data() 在 C++17 之前返回 const wchar_t *,所以现在 &amp;modName[0] 可能会更好。
  • 这就是我将data() 放入 cmets 的原因
猜你喜欢
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
  • 2011-12-04
  • 2010-09-19
相关资源
最近更新 更多