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.
I want to describe how to create a Qt-based shared or static library that is usable by a Qt-unaware program. 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.
In this example I will use the Windows program rundll32.exe
to load and execute a function that shows the Qt about dialog.
Let's say our DLL is called MyQtBasedDll.dll
, and it has a single exported function - void MyEntryPoint()
.
We will run it using the command line rundll32.exe MyQtBasedDll.dll,MyEntryPoint
. Note you need to give full paths for the exe and dll.
In order for rundll32.exe
to load and use the program, MyEntryPoint()
should have a C-calling convention. Additionally, we need a QApplication
instance to do any GUI stuff, and rundll32.exe
will obviously not create it for us.
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
.
The code of the MyEntryPoint()
function is pretty simple:
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. Note that we check for an existing instance so our DLL will work even when called by a Qt application.
Now all you need to do is substitute QMessageBox::aboutQt(0);
with your function that does useful stuff!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments