假设有2个项目. 一个是 EXE 一个是
DLLEXE是QT 项目. EXE隐式Link DLL
如果EXE里面 一个
按钮事件:
QFileDialog::getOpenFileName(this); //运行这个函数那么DLL 不会卸载.看下面最小测试代码说明可能直接一点:DLL 项目:Out.h- #pragma once
- #ifdef EXPORT
- #define DLL_API _declspec(dllexport)
- #else
- #define DLL_API _declspec(dllimport)
- #endif // EXPORT
- #include <fstream>
- class DLL_API ExportVal
- {
- public:
- ExportVal();
- ~ExportVal();
- };
- class DLL_API GlobalVarTest
- {
- public:
- GlobalVarTest()
- {
- mFS.open("Test.txt",std::ios::out);
- mFS.write("123123",sizeof("123123"));
- }
- ~GlobalVarTest()
- {
- mFS.close();
- }
- std::fstream mFS;
- };
out.cpp
- #include "Out.h"
- GlobalVarTest G_Val;
- ExportVal::ExportVal()
- {
- }
- ExportVal::~ExportVal()
- {
- }
- #include <windows.h>
- BOOL WINAPI DllMain(
- _In_ HINSTANCE hinstDLL,
- _In_ DWORD fdwReason,
- _In_ LPVOID lpvReserved
- )
- {
- if (fdwReason == DLL_PROCESS_ATTACH)
- {
- //Load lib
- int x = 100;
- }
- if (fdwReason == DLL_PROCESS_DETACH)
- {
- //UnLoad lib
- int x = 100;
- }
- return TRUE;
- }
Exe项目:
Test01.h- #ifndef TEST01_H
- #define TEST01_H
- #include <QtWidgets/QMainWindow>
- #include "ui_test01.h"
- #include "Out.h"
- class Test01 : public QMainWindow
- {
- Q_OBJECT
- public:
- Test01(QWidget *parent = 0);
- ~Test01();
- protected slots:
- void TC();
- private:
- Ui::Test01Class ui;
- };
- #endif // TEST01_H
test01.cpp
- #include "test01.h"
- #include "QPushButton"
- #include "QFileDialog"
- Test01::Test01(QWidget *parent)
- : QMainWindow(parent)
- {
- ExportVal E = ExportVal();
- QPushButton* But = new QPushButton(this);
- connect(But,&QPushButton::clicked,this,&Test01::TC);
- }
- Test01::~Test01()
- {
- }
- void Test01::TC()
- {
- QFileDialog::getOpenFileName(this);
- }
main.cpp
- #include "test01.h"
- #include <QtWidgets/QApplication>
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Test01 w;
- w.show();
- return a.exec();
- }
当你点击按钮后, 你会发现 dll 原来不会被卸载, 但是隐式连接是自动卸载的.!!!
也就是:- if (fdwReason == DLL_PROCESS_DETACH)
- {
- //UnLoad lib 这里从来没被调用过
- int x = 100;
- }
换句话说: dll里面的全局变量没被卸载...!! 析构函数没被调用.
但是如果不点击按钮,然后关闭,那么dll又会正常卸载
真蛋疼, 有谁遇见过这个问题?我在qt forums 里面也发了一片帖子, 这个问题挺纠结的 比较急 .这里是连接:http://qt-project.org/forums/viewthread/40575/ 希望大家可以随便新建一个工程 吧上面代码拷贝一下 测试一下. 我测试了很多遍, 结果都是一样.
我的环境是 VS2013 QT5.2.1 WIN8.1 64位