qt程序加载动态链接库 dll的方式

qt加载dll有四种方式

本例中qt的版本为qt5.11.3 64位

一、动态加载

使用c++的函数,动态加载


bool bRet = false;
HINSTANCE hDll = nullptr;
    hDll = LoadLibraryA("dlfs.dll");
    if(hDll != nullptr)
    {
        bRet = true;
    }

二、使用qt自带的QLibrary进行加载

bool bRet = false;
    QLibrary liba("dlfs.dll");
    if(liba.load)
    {
        bRet = true;
    }

三、静态加载

在pro中添加 lib include 有两种方式

(一) 手动 

以配置opencv为例,在pro中直接填写如下内容即可

INCLUDEPATH += $$PWD/3rdparty/opencv/2.4.3/include/
INCLUDEPATH += $$PWD/3rdparty/opencv/2.4.3/include/opencv/
INCLUDEPATH += $$PWD/3rdparty/opencv/2.4.3/include/opencv2/

LIBS += -L$$PWD/3rdparty/opencv/2.4.3/x64/lib/ -lopencv_core243d

(二)自动

项目-----添加库---外部库-- 选择 库文件 和 库路径 点击确定后即 在pro中生成如下的内容。

也可以不按照此步骤,直接在pro中添加如下的代码即可

最后在pro中生成的为: 

INCLUDEPATH += $$PWD/3rdparty/opencv-4.2.0/include
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_core420
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_core420d

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/./3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_imgcodecs420
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_imgcodecs420d

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/./3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_imgproc420
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_imgproc420d

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/./3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_videoio420
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/./3rdparty/opencv-4.2.0/win10/x64/vc15/lib/ -lopencv_videoio420d

四、出现的问题

qt动态加载dll出现的问题

在使用LoadLibraryA加载动态链接库时,得到的句柄为空

如果发现动态加载dll时 hDll为空,而dll的路径是正确的,这时就要考虑dlff1.dll 的位数与qt程序是否一致了。


HINSTANCE hDll = LoadLibraryA("dlff1.dll");

qt程序为64位,通过dumbin.exe 发现dlff1.dll为32位的,为了使用方便,要求dlff1.dll 改为64位的dll,重新构建项目,输出x64位的dlff1.dll