Search code examples
c++visual-studiochartype-conversiontchar

Am I converting properly from "const char *" to "TCHAR*"?


I'm trying to pass a process name as a TCHAR to the following void:

void GetBaseAddressByName(DWORD pID, TCHAR *pN)    

By doing it like this:

GetBaseAddressByName(aProcs[i], (TCHAR*)"Process.exe");

So my question is: is what I am doing correct? Because I have tried both TEXT("Process.exe") and _T("Process.exe") with my project's Character Set both on Multi-Bite and Unicode and it just tells me that

argument of type "const char*" is incompatible with parameter of type "TCHAR*"

Solution

  • (TCHAR*)"Process.exe" is not a valid type-cast. It will "work" when the project charset is set to ANSI/MBCS, but it will produce garbage if the charset is set to Unicode.

    Using TEXT("Process.exe") is the correct way to make a string literal use TCHAR characters.

    GetBaseAddressByName(aProcs[i], TEXT("Process.exe"));
    

    However, you need to change your pN parameter to const TCHAR * (or LPCTSTR) instead:

    void GetBaseAddressByName(DWORD pID, const TCHAR *pN);
    

    void GetBaseAddressByName(DWORD pID, LPCTSTR pN);
    

    A string literal is const data, and you cannot pass a pointer-to-const-data where a pointer-to-non-const-data is expected (without casting the const away with const_cast). That is why you were still getting errors when trying to use the TEXT()/_T() macros.