在旧式main()的参数中分解WinMain的cmdLine

时间:2010-02-27 05:23:12

标签: c++ c windows winapi

我想将WinMain的{​​{1}}参数转换为cmdLineargc,以便我可以使用我为控制台应用程序编写的参数解析函数。

除了我想支持“引号”之外,这将是微不足道的。例如:

argv

应该是

test.exe test1 test2 "testing testing"

我意识到cmdLine没有程序名(argv [0]);这无关紧要,我可以使用虚拟值。

我正在考虑使用正则表达式进行此操作,argv[0] = "test.exe"; argv[1] = "test1"; argv[2] = "test2"; argv[3] = "testing testing"; 我不确定它的效果如何......可能不是很好?在windows api中是否有任何功能?感谢

4 个答案:

答案 0 :(得分:22)

如果您使用的是Microsoft编译器,则__argc中定义了公共符号__argv__wargvstdlib.h。这也适用于使用Microsoft运行时库的MinGW。

答案 1 :(得分:5)

CommandLineToArgvW看起来在这里会有所帮助。

答案 2 :(得分:2)

基于Denis K的回应

请参阅:https://msdn.microsoft.com/library/dn727674.aspx

这会将Windows特定入口点添加到应用的clasic起点:

int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char*, int nShowCmd)
{
    return main(__argc, __argv);
}

答案 3 :(得分:0)

如果你想要普通的int argc,char ** argv参数,你必须自己做。

void fetchCmdArgs(int* argc, char*** argv) {
    // init results
    *argc = 0;

    // prepare extraction
    char* winCmd = GetCommandLine();
    int index = 0;
    bool newOption = true;
    // use static so converted command line can be
    // accessed from outside this function
    static vector<char*> argVector;

    // walk over the command line and convert it to argv
    while(winCmd[index] != 0){
        if (winCmd[index] == ' ') {
            // terminate option string
            winCmd[index] = 0;
            newOption = true;

        } else  {
            if(newOption){
                argVector.push_back(&winCmd[index]);
                (*argc)++;  
            }
            newOption = false;
        }
        index++;
    }

    // elements inside the vector are guaranteed to be continous
    *argv = &argVector[0];
}


// usage
int APIENTRY WinMain(...) {
    int argc = 0;
    char** argv;
    fetchCmdArgs(&argc, &argv);
}