如何从Qt中的另一个应用程序调用DLL

How to call DLL from another application in Qt

本文关键字:另一个 应用程序 调用 DLL Qt      更新时间:2023-10-16

我是Qt开发和开发启动TCP Server的Qt DLL的新手。当我从另一个应用程序调用dll时,它不会收到任何新的连接套接字。因此,如果我做错了任何步骤,请指导我。

服务器.h

extern "C" SERVERSHARED_EXPORT void CallServer();
class SERVERSHARED_EXPORT Server :  public QObject
{
    Q_OBJECT
public:
    Server();
    void CallServer();
    void CallServer1();
    QTcpServer *server;
    QTcpSocket *socket ;
signals:
public slots:
    void myConnection();
    void closingClient();
};

服务器.cpp

  Server::Server()
{
}
void CallServer()
{
    Server server_Obj;
    server_Obj.CallServer1();
    while (true)
        ::sleep(1000);
}
void Server::CallServer1()
{
    server = new QTcpServer(this);
    connect(server, SIGNAL(newConnection()),this, SLOT(myConnection()));
    QHostAddress hostadd(ServerIP);
    qDebug() << ServerIP;
    qDebug() << Port;
    if(!server->listen(hostadd,Port.toInt()))        qDebug() << "nWeb server     could not start";
    else                                             qDebug() <<"nWeb server is waiting for a connection";
}
void Server::myConnection()
{
    qDebug() << "Detected Connection";
    QByteArray Rdata;
    socket = server->nextPendingConnection();
    qDebug() << "Wait for connect = " << socket->waitForConnected();
    while (socket->waitForReadyRead(10))
    {
        while(socket->bytesAvailable() > 0)
        {
            Rdata.append(socket->readAll());
        }
    }
    qDebug() << "Final Testing is size = " << Rdata.size();
    qDebug() << "Final Testing is" << Rdata;
}

.pro 文件

QT       += core
QT       += network
QT      += widgets
QT       -= gui
TARGET = Server
TEMPLATE = lib
DEFINES += SERVER_LIBRARY
SOURCES += server.cpp 
HEADERS += server.h
        server_global.h 

另一个应用程序:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QLibrary library("Server.dll");
     if (!library.load())
        qDebug() << library.errorString();
     if (library.load())
         qDebug() << "library loaded";
     typedef int(*pf)(void);
     pf cwf = (pf)library.resolve("CallServer");
     if (cwf) {
      int x = cwf();
     } else {
      qDebug() << "Could not show widget from the loaded library";
     }
     qDebug() << "After call";
    return a.exec();
}

看起来它不起作用,因为您以异步(信号/插槽)方式使用 QTcpSocket(您的服务器类)而没有事件循环 - 所以它不起作用。您应该添加事件循环或以阻塞方式使用套接字。有关更多详细信息,请查看 - http://doc.qt.io/qt-5/qtnetwork-blockingfortuneclient-example.html