【问题标题】:Using Qt-DLL in Python在 Python 中使用 Qt-DLL
【发布时间】:2015-03-03 14:51:55
【问题描述】:

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

部署dll.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

部署dll.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

我正在使用带有 MSVC2012 64 位编译器的 Windows 7 64 位、Python 2.7.3 和 Qt 5.2.1。

【问题讨论】:

    标签: python c++ qt dll


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果你只是在DllMain 中调用QApplication::exec(),这将完全阻塞主线程。所以QApplication::exec()QtConcurrent::run 的异步调用包装。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-30
        • 1970-01-01
        • 1970-01-01
        • 2011-04-20
        • 2011-01-10
        • 2017-06-09
        相关资源
        最近更新 更多