September 16th, 2010

How is the CommandLineToArgvW function intended to be used?

The CommandLineToArgvW function does some basic command line parsing. A customer reported that it was producing strange results when you passed an empty string as the first parameter:

LPWSTR argv = CommandLineToArgvW(L"", &argc);

Well, okay, yeah, but huh?

The first parameter to CommandLineToArgvW is supposed to be the value returned by GetCommandLineW. That’s the command line, and that’s what CommandLineToArgvW was designed to parse. If you pass something else, then CommandLineToArgvW will try to cope, but it’s not really doing what it was designed for.

It turns out that the customer was mistakenly passing the lpCmdLine parameter that was passed to the wWinMain function:

int WINAPI wWinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPWSTR lpCmdLine,
    int nCmdShow)
{
    int argc;
    LPWSTR argv = CommandLineToArgvW(lpCmdLine, &argc);
    ...
}

That command line is not in the format that CommandLineToArgvW expects. The CommandLineToArgvW function wants the full, unexpurgated command line as returned by the GetCommandLineW function, and it breaks it up on the assumption that the first word on the command line is the program name. If you hand it an empty string, the CommandLineToArgvW function says, “Whoa, whoever generated this command line totally screwed up. I’ll try to muddle through as best I can.”

Next time, we’ll look at the strange status of quotation marks and backslashes in CommandLineToArgvW.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.