简体   繁体   English

使用C程序中的Qt库

[英]Using a Qt library from a C program

Qt is great for building applications, but once or twice I have wanted to show a nice Qt dialog from an existing application that is written in pure C. Qt非常适合构建应用程序,但有一两次我想用纯C编写的现有应用程序显示一个很好的Qt对话框。

I want to describe how to create a Qt-based shared or static library that is usable by a Qt-unaware program. 我想描述如何创建一个Qt-unaware程序可以使用的基于Qt的共享或静态库。 To narrow down the problem, let's assume that we call a function that shows some dialogs or widgets, and does not return until all dialogs have been closed. 为了缩小问题范围,让我们假设我们调用一个显示一些对话框或小部件的函数,并且在所有对话框都关闭之前不会返回。 Otherwise it can't be done without some 'cooperation' from the hosting process - it has to at least run the message pump for Qt. 否则,如果没有来自托管过程的一些“合作”,它就无法完成 - 它必须至少为Qt运行消息泵。

In this example I will use the Windows program rundll32.exe to load and execute a function that shows the Qt about dialog. 在这个例子中,我将使用Windows程序rundll32.exe来加载和执行一个显示Qt about对话框的函数。

Let's say our DLL is called MyQtBasedDll.dll , and it has a single exported function - void MyEntryPoint() . 假设我们的DLL名为MyQtBasedDll.dll ,它有一个导出函数 - void MyEntryPoint()

We will run it using the command line rundll32.exe MyQtBasedDll.dll,MyEntryPoint . 我们将使用命令行rundll32.exe MyQtBasedDll.dll,MyEntryPoint运行它。 Note you need to give full paths for the exe and dll. 请注意,您需要为exe和dll提供完整路径。

In order for rundll32.exe to load and use the program, MyEntryPoint() should have a C-calling convention. 为了让rundll32.exe加载并使用该程序, MyEntryPoint()应具有C调用约定。 Additionally, we need a QApplication instance to do any GUI stuff, and rundll32.exe will obviously not create it for us. 另外,我们需要一个QApplication实例来做任何GUI的东西,而rundll32.exe显然不会为我们创建它。

To create the Qt library with Qt Creator, we can choose File->New File or Project->Libraries->C++ Library , and the project name should be MyQtBasedDll . 要使用Qt Creator创建Qt库,我们可以选择File-> New File或Project-> Libraries-> C ++ Library ,项目名称应该是MyQtBasedDll

The code of the MyEntryPoint() function is pretty simple: MyEntryPoint()函数的代码非常简单:

extern "C"
{
__declspec(dllexport) void MyEntryPoint()
{
    if (!QApplication::instance()) {
        QApplication a(__argc, __argv);
        QMessageBox::aboutQt(0);
    } else {
        QMessageBox::aboutQt(0);
    }
}
}

This function can be called multiple times by the same exe, and each time a new QApplication object is constructed, only for the duration of the function. 此函数可以由同一个exe多次调用,并且每次构造一个新的QApplication对象时,仅在函数的持续时间内。 Note that we check for an existing instance so our DLL will work even when called by a Qt application. 请注意,我们检查现有实例,以便即使在Qt应用程序调用时我们的DLL也能正常工作。

Now all you need to do is substitute QMessageBox::aboutQt(0); 现在您需要做的就是替换QMessageBox::aboutQt(0); with your function that does useful stuff! 用你的功能做有用的东西!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM