gpt4 book ai didi

windows - CommandLineToArgvW 怪癖

转载 作者:行者123 更新时间:2023-12-02 00:20:26 32 4
gpt4 key购买 nike

我有一个小的 win32 程序,它使用给定的 lpCmdLine 调用 CommandLineToArgvW

int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
(void)hInstance;
(void)hPrevInstance;
(void)nCmdShow;
int argc;
LPTSTR* argv = CommandLineToArgvW(lpCmdLine, &argc);
MessageBoxW(0, lpCmdLine, TEXT("lpCmdLine"), MB_OK );

for(int i=0; i<argc;++i){
MessageBoxW(0, argv[i], TEXT("argv"), MB_OK );
}
return 0;
}

我观察到的奇怪的事情是:

  • 如果我调用不带参数的程序,lpCmdLine 是空字符串,CommandLineToArgvW 返回 1 个参数 - 可执行路径。
  • 如果带参数调用,CommandLineToArgvW 返回准确数量的参数,没有可执行文件

我找不到这种奇怪行为的记录。

我错过了什么?我是否以意外的方式使用了该命令?

最佳答案

这是记录在案的行为。

根据 CommandLineToArgvW() :

lpCmdLine

Type: LPCWSTR

Pointer to a null-terminated Unicode string that contains the full command line. If this parameter is an empty string the function returns the path to the current executable file.

这意味着 CommandLineToArgvW() 仅当 lpCmdLine 参数为 null 或如果它显式包含可执行文件名称时才返回调用可执行文件名称.

请注意,CommandLineToArgvW() 需要完整的命令行。但是,根据 WinMain() :

lpCmdLine

Type: LPSTR

The command line for the application, excluding the program name. To retrieve the entire command line, use the GetCommandLine function.

因此,当您执行不带参数的程序时,WinMainlpCmdLine 参数为空,CommandLineToArgvW() 仅返回可执行文件姓名。但是,如果您使用参数执行程序,lpCmdLine 参数不是空的,但不包含可执行文件名称,因此 CommandLineToArgvW() 仅返回参数而没有可执行文件名称。

因此,您需要按照 WinMain() 文档中的说明进行操作,并使用 GetCommandLine() 而不是 lpCmdLineCommandLineToArgvW() 文档中也说明了这一点:

The GetCommandLineW function can be used to get a command line string that is suitable for use as the lpCmdLine parameter.

所以,改用这个:

LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);

关于windows - CommandLineToArgvW 怪癖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55544279/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com