0

error C2440: 'initializing': cannot convert from 'TCHAR [260]' to 'std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>

I get this error, been stuck on this for a few hours..

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
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
develping
  • 1
  • 1
  • 6
    At least you didn't apply an erroneous C-style cast to get rid of the error, like so many seem to do (and then wonder why their program crashes or their strings look weird). I give kudos to that. – PaulMcKenzie Mar 30 '18 at 18:56
  • Possible dup of https://stackoverflow.com/questions/6291458/how-to-convert-a-tchar-array-to-stdstring ? – user3486184 Mar 30 '18 at 20:23

1 Answers1

2

TCHAR is defined as either char or wchar_t depending on whether you have the UNICODE macro defined. In your case, it looks like it is not defined, so you are trying to construct a std::wstring from a char[] array.

I would advise you to always use wide APIs on Windows, because that is the only way to get proper Unicode support on there:

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

wstring modName = szModName;

GetModuleFileNameEx is not a function, but rather is a macro that expands to either GetModuleFileNameExA or GetModuleFileNameExW depending on the UNICODE macro.

Originally, the TCHAR variants were provided to ease transition from old Windows versions without Unicode support to newer NT-based Windows versions with Unicode support. Nowadays, there is no reason to use the ANSI variants at all.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Alternatively, you can do away with the temp buffer and receive the filename into the `std::wstring` directly, eg: `wstring modName(MAX_PATH, 0); DWORD len = GetModuleFileNameExW(hProcess, hMods[i], &modName[0] /* or: modName.data() */, MAX_PATH); if (!len) continue; modName.resize(len);` – Remy Lebeau Mar 30 '18 at 19:04
  • @RemyLebeau `data()` returns `const wchar_t *` before C++17, so `&modName[0]` might be better for now. –  Mar 30 '18 at 19:10
  • that is why i put `data()` in comments – Remy Lebeau Mar 30 '18 at 19:12