在Python中使用Qt-DLL

时间:2015-03-03 14:51:55

标签: python c++ qt dll

我正在创建一个使用Qt的DLL。我需要从Python访问此DLL。 这是一个示例代码:

deploydll.pro:

QT       += core gui \
        xml \
        declarative

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TEMPLATE = lib
CONFIG += console

TARGET = DeployDll

DEFINES += DEPLOY_LIBRARY

SOURCES += \
    deploydll.cpp

HEADERS += \
    deploydll.h

deploydll.h:

#ifndef DEPLOYDLL_H
#define DEPLOYDLL_H

#include <iostream>

#if defined DEPLOY_LIBRARY
#define DEPLOY_EXPORT __declspec(dllexport)
#else
#define DEPLOY_EXPORT __declspec(dllimport)
#endif

class DEPLOY_EXPORT DeployDll
{
public:
    DeployDll();
    bool showMessage();
};

#endif // DEPLOYDLL_H

#deploydll.cpp

#include "deploydll.h"

#include <functional>

#define NOMINMAX
#include <Windows.h>

#include <QApplication>
#include <QMessageBox>
#include <QtConcurrent/QtConcurrent>

QApplication* a = 0;
int* argc = 0;

BOOL WINAPI DllMain( HANDLE hDll, DWORD dwReason, LPVOID lpReserved )
{
    switch( dwReason )
    {
    case DLL_PROCESS_ATTACH:
    {
        argc = new int( 0 );
        QApplication* a = new QApplication( *argc, 0 );
        QtConcurrent::run( &QApplication::exec );
    }
    case DLL_PROCESS_DETACH:
        if( argc != 0 )
        {
            delete argc;
            argc = 0;
        }

        if( a != 0 )
        {
            delete a;
            a = 0;
        }
        break;
    case DLL_THREAD_ATTACH:
        break;
    case DLL_THREAD_DETACH:
        break;
    }

    return TRUE;
}

DeployDll::DeployDll()
{
    std::cout << "Constructor called!\n";
}

bool DeployDll::showMessage()
{
    std::cout << "Method called!\n";

    QMessageBox msgBox;
    msgBox.setText("Method called!");
    msgBox.exec();

    return true;
}

这是一个示例python代码:

from ctypes import *

if __name__ == '__main__':
    print "Started main!"
    cdll.LoadLibrary("DeployDll")

我将Qt平台文件夹添加到C:\ python27文件夹中。 生成的DLL位于python项目的文件夹中。

如果我在一个简单的C ++程序中使用DLL它可以工作,但是当我执行python脚本时,我收到以下错误消息:

Started main!
QApplication::exec: Must be called from the main thread
QWaitCondition: Destroyed while threads are still waiting

我正在使用Windows 7 64位,Python 2.7.3和Qt 5.2.1以及MSVC2012 64位编译器。

2 个答案:

答案 0 :(得分:0)

Meybe你应该在主线程中使用QApplication :: exec()。你为什么使用QtConcurrent :: run?

答案 1 :(得分:0)

如果您只是在QApplication::exec()中调用DllMain,则会完全阻止主线程。所以QApplication::exec()QtConcurrent::run的异步调用包装。