Search code examples
c++casting

Convert const wchar_t* to LPWSTR


I'm trying to convert a const wchar_t* to LPWSTR but I'm getting the error E0513.

I'm using Visual Studio with C++17.

Here is my code:

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    LPWSTR* argv;
    int argCount;

    argv = CommandLineToArgvW(GetCommandLineW(), &argCount);

    if (argv[1] == nullptr) argv[1] = L"2048"; <-- conversion error
}

How to fix this?


Solution

  • To answer your question:

    You can use const_cast:

    argv[1] = const_cast<LPWSTR>(L"2048");
    

    Or a local wchar_t[] array:

    wchar_t arg[] = L"2048";
    argv[1] = arg;
    

    However, CommandLineToArgvW() will never return any array elements set to nullptr to begin with. All array elements are null-terminated string pointers, so empty parameters would have to be specified as quoted strings ("") on the command-line in order to be parsed, and as such will be returned as 0-length string pointers in the array. So, you would need to check for that condition instead, eg:

    if (argCount > 1 && *(argv[1]) == L'\0')