简体   繁体   中英

C2664 error, C++ which is foreign to me

The error I get is:

"DWORD GetModuleFileNameW(HMODULE,LPWSTR,DWORD)' : cannot convert parameter 2 from 'char *' to 'LPWSTR"

On this line

GetModuleFileName(NULL, &strL[0], MAX_PATH);

This the code

    BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved)
{
    switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
        {
            std::string strL;
            strL.resize(MAX_PATH);
            GetModuleFileName(NULL, &strL[0], MAX_PATH);

            DisableThreadLibraryCalls(hModule);

            if(strL.find("notepad.exe") != std::string::npos)
            {
                gl_hThisInstance = hModule;

                LoadOriginalDll();
            }

            break;
        }
    case DLL_PROCESS_DETACH:
        {
            ExitInstance();

            break;
        }
    }
    return TRUE;
}

From MSDN ,

typedef wchar_t* LPWSTR, *PWSTR;

So it is expecting a wchar_t * (wchar_t is 2 bytes or more), but &std::string[0] is a char* (char is a byte). You need to use std::wstring instead:

std::wstring strL;

If you want your code to compile without using wide strings, refer to here:

How do I turn off Unicode in a VC++ project?

Chances are if Unicode is enabled in VC++, there are defines like this:

#ifdef UNICODE
#define CreateFile  CreateFileW
#else
#define CreateFile  CreateFileA
#endif // !UNICODE

Fix:

Have you tried: Project Properties - General - Project Defaults - Character Set?

See answers in this question for the differences between "Use Multi-Byte Character Set" and "Not Set" options: About the "Character set" option in visual studio 2010

And from the link inside the quote:

It is a compatibility setting, intended for legacy code that was written for old versions of Windows that were not Unicode enabled. Versions in the Windows 9x family, Windows ME was the last one. With "Not Set" or "Use Multi-Byte Character Set" selected, all Windows API functions that take a string as an argument are redefined to a little compatibility helper function that translates char* strings to wchar_t* strings, the API's native string type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM