Search code examples
visual-studioqtwinmainqapplication

Why winmain parameters doesn't match to each other?


Why QApp constructor fails with WinMain parameters?

 int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPTSTR _lpCmdLine, int _nShowCmd) {
    QApplication app(_nShowCmd, & _lpCmdLine);

And here it fail with exception:

Exception at adress 0x0F3621DC (Qt5Guid.dll) in updater_app.exe: 0xC0000005

Whats wrong? how to fix it?

UPD:

And it works in such way:

int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPTSTR _lpCmdLine, int _nShowCmd) {

int nShowCmd(0);
QApplication app(nShowCmd, & _lpCmdLine);

_lpCmdLine is 10 and _nShowCmd is empty string - so it doesn't match. Why?


Solution

  • The Qt application QApplication main object supposed to be created in the standard main function:

    int main(int argc, char *argv[])
    {
       QApplication app(argc, argv);
       // more app objects initialization
       return app.exec();
    }
    

    and you do:

    int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPTSTR _lpCmdLine, int _nShowCmd)
    {
       QApplication app(nShowCmd, & _lpCmdLine);
       return app.exec();
    }
    

    Which implies that &_lpCdLine being equivalent to argv but:

    LPTSTR _lpCmdLine which is an equivalent to char* and you take an address of it so &_lpCmdLine matches char** when _lpCmdLine is pointing to a contiguous buffer of characters and not an array of character strings as argv.

    It makes sense to consider how main() function is implemented on Windows. There is a good discussion: WINMAIN and main() in C++ (Extended) Mind that the C runtime must be initialized before main() function runs and that may depend on compiler/linker. And also find an example of Qt application main function.

    I guess that the case when you make your code not to crash by introducingn nShowCmd == 0 makes QApplication object not to read the command line which prevents an incorrect access via random content interpreted as addresses in _lpCmdLine. But that is still wrong and an incomplete intitialization of QApplication object.

    The authors fails to see the window and sees the console instead and that relates to incomplete code of main function not launching any window. Also, QML application main.cpp might help.