首页 > 解决方案 > 将 const wchar_t* 转换为 LPWSTR

问题描述

我正在尝试将 a 转换为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
}

如何解决这个问题?

标签: c++casting

解决方案


要回答您的问题:

您可以使用const_cast

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

或本地wchar_t[]数组:

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

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

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

推荐阅读