c++charlpwstr

Can't convert Char to LPWSTR


The following code

string exePath() {
string path;
char buffer[MAX_PATH];
cout << "reading path\n";
GetModuleFileName(NULL, buffer, MAX_PATH);
string::size_type pos = string(buffer).find_last_of("\\/");
path = string(buffer).substr(0, pos)/*+"\\system.exe"*/;
return path;

}

gives me error at the second parameter in VisualStudio (buffer):

the type "char *" argument is incompatible with the type parameter "LPWSTR"

(translated from italian,i have vs in italian, hope you understand) and can't convert Char to LPWSTR in the 2 argument

This code compiles fine with code::blocks and dev c++ but in vs it doesn't


Solution

  • Because GetModuleFileName is a macro definition for GetModuleFileNameW if UNICODE is defined and which requires wchar_t*. If no UNICODE is defined then GetModuleFileName resolves to GetModuleFileNameA. The simple fix for you is to use explicitly GetModuleFileNameA which accepts char*

    This code compiles fine with code::blocks and dev c++ but in vs it doesn't

    most probably because with code::blocks you compile with no UNICODE defined, while under VS by default UNICODE is defined.

    If you are not using UNICODE, and want to stay with multibyte string (same as in code::blocks) you can disable UNICODE in your Visual Studio build by changing in project properties on General tab -> Character set to Use Multi-Byte Character Set.

    [edit]

    To avoid problems with UNICODE characters in the path it is recomended to use UNICODE. This requires you to use std::wstring which is specialization for wchar_t, also instead of char buffer[MAX_PATH]; you should use wchar_t buffer[MAX_PATH];. cout << "reading path\n"; would have to be wcout << L"reading path\n";. You can also use macros like TCHAR or _T("reading path"), to make it independently work for UNICODE and non-UNICODE builds.