PDA

View Full Version : Loading Qt DLL from MFC



red1ynx
4th May 2011, 13:36
I load my qt-dll by button clicking:


void CMFCTestDlg::OnBnClickedButton1()
{
HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

// Get a handle to the DLL module.

hinstLib = LoadLibrary(TEXT("qttest.dll"));

// If the handle is valid, try to get the function address.

if (hinstLib != NULL)
{
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "createWindow");

// If the function address is valid, call the function.

if (NULL != ProcAdd)
{
fRunTimeLinkSuccess = TRUE;
char * params[] = {"1"};
(ProcAdd) (1, params);
}

// Free the DLL module.

fFreeResult = FreeLibrary(hinstLib);
}

// If unable to call the DLL function, use an alternative.

if (! fRunTimeLinkSuccess)
MessageBox(L"Message printed from executable\n");
}


Function createWindow() is as follows:

extern "C" __declspec(dllexport) int createWindow(int argc, char *argv[])
{
new QApplication(argc, argv);
Q_CHECK_PTR( qApp );

MainWindow* w = MainWindow::getInstance();
qApp->setMainWidget(w);
w->show();

return qApp->exec();
}

When I click button then MainWindow appears, I close that window and then I click button again -- raising up assert: qcoreapplication: there should be only one application object...

Then I wrote the following code:

void MainWindow::closeEvent(QCloseEvent * event)
{
qApp->exit();
delete qApp;
}

But now i'm getting error in _CrtIsValidHeapPointer method after second closing of MainWindow.

How to unload qt-dll correctly?

wysota
4th May 2011, 19:30
I'd simply check if qApp is a valid pointer before creating a new application object.

red1ynx
10th May 2011, 15:12
Don't work.

high_flyer
10th May 2011, 15:37
First a comment:
Not sure what the effect of this code is:

void MainWindow::closeEvent(QCloseEvent * event)
{
qApp->exit();
delete qApp;
}
because your window is the main application window, the application will destroy it as part of its exit process.
But you are deleting the application before you are deleting the window, so I am not sure if it ends in a defined state, and if so what that state is.

You can however try:

void MainWindow::closeEvent(QCloseEvent * event)
{
qApp->exit();
delete qApp; //this leaves garbage in the pointer.
qApp = NULL;
}