将 const wchar_t* 转换为 LPWSTR

Convert const wchar_t* to LPWSTR

我正在尝试将 const wchar_t* 转换为 LPWSTR,但出现错误 E0513。

我在 C++17 中使用 Visual Studio。

这是我的代码:

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
}

如何解决这个问题?

回答你的问题:

您可以使用 const_cast:

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

或本地 wchar_t[] 数组:

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

但是,CommandLineToArgvW() 永远不会 return 任何数组元素设置为 nullptr 开头。所有数组元素都是以 null 结尾的字符串指针,因此必须在命令行上将空参数指定为带引号的字符串 ("") 才能被解析,因此将被 returned作为数组中的 0 长度字符串指针。因此,您需要检查该条件,例如:

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