如何在使用 QtNetwork 和 QThread 的 QT DLL 中正确关闭 QCoreApplication?

问题描述

我正在尝试创建一个 QT DLL 以在 InnoSetup 安装程序中使用它(InnoSetup 是用 Delphi Pascal 编写的)。

当从 InnoSetup 调用时,此 DLL 应具有从 Internet 下载文件功能

InnoSetup 调用是这样进行的:

procedure downloadFile();
  external 'dodownload@files:testdll.dll,libssl-1_1.dll,libcrypto-1_1.dll stdcall loadwithalteredsearchpath delayload';

然后,我用这个来称呼它:

function InitializeSetup(): Boolean;
begin
  Result := True;
  ExtractTemporaryFile('testdll.dll');
  downloadFile();
end;

问题是,我不能重用 downloadFile(); 如果我需要稍后调用它(在初始调用之后),因为在第一次调用时,不知何故,我怀疑,QCoreApplication 没有正确关闭并保持在执行循环中。 当我第二次调用函数时,没有任何反应,也没有从 Internet 下载文件。再次下载文件的唯一方法关闭并重新打开 Inno Setup。

这是我的代码

TESTDLL.pro

QT -= gui
QT += network

TEMPLATE = lib
DEFInes += TESTCLASS_LIBRARY

CONfig += c++11 dll

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so,uncomment the following line.
# DEFInes += QT_disABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    testdll.cpp \
    libs\downloadThread.cpp

HEADERS += \
    testdll_global.h \
    testdll.h \
    libs\downloadThread.h

QMAKE_LFLAGS += -Wl,--output-def,testdll.def

# Default rules for deployment.
unix {
    target.path = /usr/lib
}
!isEmpty(target.path): INSTALLS += target

TESTDLL.h

#ifndef TESTDLL_H
#define TESTDLL_H

#include <QtCore>

#include "testdll_global.h"
#include "libs/downloadThread.h"


class TestDLL : public QObject
{
    Q_OBJECT
public slots:
    void handleResults(const QString &);
    void startWThread();
    void initQCoreApp();

private:
    void debugMsg(QString fileName,QString message)
    {
        QFile file(fileName);
        file.open(qiodevice::writeonly | qiodevice::Text);
        QTextStream out(&file);
        out << message;
        file.close();
    };
};

#endif

TESTDLL.cpp

#include "testdll.h"

namespace QCoreAppDLL
{
    static int argc = 1;
    static char arg0[] = "testdll.cpp";
    static char * argv[] = { arg0,nullptr };
    static QCoreApplication * pApp = nullptr;
}

extern "C" TESTCLASS_EXPORT void dodownload()
{
    TestDLL a;
    a.initQCoreApp();
}

void TestDLL::startWThread()
{
    downloadThread *thread = new downloadThread(this);
    connect(thread,&downloadThread::finished,thread,&QObject::deleteLater);
    connect(thread,&downloadThread::resultReady,this,&TestDLL::handleResults);
    thread->start();
}

void TestDLL::initQCoreApp()
{

    if (!QCoreApplication::instance())
    {
        QCoreAppDLL::pApp = new QCoreApplication(QCoreAppDLL::argc,QCoreAppDLL::argv);

        TestDLL a;
        a.startWThread();

        QCoreAppDLL::pApp->exec();
    }
}

void TestDLL::handleResults(const QString &)
{
    debugMsg("result.txt","succes!");

    if (QCoreAppDLL::pApp)
        QCoreAppDLL::pApp->quit();
}

DOWNLOADTHREAD.h

#ifndef downloadThread_H
#define downloadThread_H

#include <QtNetwork>
#include <QDebug>

class downloadThread : public QThread
{
    Q_OBJECT
signals:
    void resultReady(const QString &s);
public:
    downloadThread(QObject *parent);
    ~downloadThread();

    void run() override {
        QString result;

        initDownload();

        emit resultReady(result);
    };
    void initDownload();
    void dodownload(QString url);
private:
    QNetworkAccessManager *networkMgr;
    QNetworkReply *_reply;
public slots:
  void replyFinished(QNetworkReply * reply);
};
#endif

DOWNLOADTHREAD.cpp

#include "downloadThread.h"

downloadThread::downloadThread(QObject *parent)
    : QThread(parent)
{
}

downloadThread::~downloadThread()
{
   quit();
   wait();
}

void downloadThread::initDownload()
{
    dodownload("http://www.google.com");
    exec();
}

void downloadThread::dodownload(QString url)
{
    networkMgr = new QNetworkAccessManager;

    qnetworkrequest request;
    request.setUrl(QUrl(url));
    networkMgr->get(request);

    connect(networkMgr,SIGNAL(finished(QNetworkReply*)),SLOT(replyFinished(QNetworkReply*)));
}

void downloadThread::replyFinished(QNetworkReply * reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray content = reply->readAll();
        QSaveFile file("output.txt");
        file.open(qiodevice::writeonly);
        file.write(content);
        file.commit();

        reply->deleteLater();
        this->exit();
    } else {
        //error
        reply->deleteLater();
        this->exit();
    }
}

我自己尝试解决问题的方法

  • 使用删除QCoreAppDLL::pApp
void TestDLL::handleResults(const QString &)
{
    debugMsg("result.txt","succes!");

    if (QCoreAppDLL::pApp){
        QCoreAppDLL::pApp->quit();
        delete QCoreAppDLL::pApp;
    }
}

使宿主应用程序崩溃。

  • QTimerSLOT(quit()) 的使用,
void TestDLL::initQCoreApp()
{

    if (!QCoreApplication::instance())
    {
        QCoreAppDLL::pApp = new QCoreApplication(QCoreAppDLL::argc,QCoreAppDLL::argv);

        TestDLL a;

        connect(&a,SIGNAL(finished()),QCoreAppDLL::pApp,SLOT(quit()));
        QTimer::singleShot(0,&a,SLOT(startWThread));

        QCoreAppDLL::pApp->exec();
    }
}

什么也没发生,就像 QCoreApplication exec 循环在 QThread 完成工作之前结束一样。

  • 在 QThread 对象上使用插槽/信号,
void TestDLL::startWThread()
{
    downloadThread *thread = new downloadThread(this);
    connect(thread,&TestDLL::handleResults);
    connect(thread,qApp,SLOT(quit()));
    thread->start();
}

具有与以下相同的行为:

void TestDLL::handleResults(const QString &)
{
    debugMsg("result.txt","succes!");

    if (QCoreAppDLL::pApp)
        QCoreAppDLL::pApp->quit();
}

我没有想法,我还能做些什么来解决这个问题?

提前谢谢各位!

解决方法

我终于自己解决了这个难题。有兴趣的朋友可以看看。

我创建了一个新函数:

void TestDLL::deinitQCoreApp()
{
    if (QCoreAppDLL::pApp)
        delete qApp;
}

现在,我的外部函数变成了:

extern "C" TESTCLASS_EXPORT void doDownload()
{
    TestDLL a;
    a.initQCoreApp();

    TestDLL b;
    b.deinitQCoreApp();
}

当然,TESTDLL.h 有一个新条目:

#ifndef TESTDLL_H
#define TESTDLL_H

#include <QtCore>

#include "testdll_global.h"
#include "libs/downloadThread.h"


class TestDLL : public QObject
{
    Q_OBJECT
public slots:
    void handleResults(const QString &);
    void startWThread();
    void initQCoreApp();
    void deinitQCoreApp();

private:
    void debugMsg(QString fileName,QString message)
    {
        QFile file(fileName);
        file.open(QIODevice::WriteOnly | QIODevice::Text);
        QTextStream out(&file);
        out << message;
        file.close();
    };
};

#endif

现在,我可以在主机上重复使用该功能多少次。 问题解决了!