Qt文档阅读笔记-QLibrary基本概念及实例

QLibrary类是在程序运行时加载动态动态链接库的。

 

可以通过使用构造函数添加需要加载的链接库路径,或者使用setFileName()函数设置路径。如果是绝对路径就直接加载,如果是相对路径QLibrary会在相当路径及所有环境变量中寻找。

 

如果都找不到,会通过平台的不同,去加对应的.so或.dll文件。

 

这个意思就是,当在windows上加载lib库的参数为demo,那么QLibrary会在后面加.dll。如果是linux就会加.so。

 

通过调用load()函数加载链接库,使用isLoad()函数去判断加载是否成功,使用resolve()与load()差不多,但是当如果load失败,将会尝试再次加载。当经过一次加载后,链接库将会存储到内存中直到应用程序退出。使用unload()函数解除,如果有多个QLibrary使用了同一个动态链接库unload()将返回false。直到最后一个QLibrary解除,才会成功。

 

这里有2个概念:

显式链接:直接在代码中解析出函数名,这种方式叫显式。

隐式链接:在程序构建过程中参与链接过程。

这里有个要注意的此处只能搞C的dll,不能搞c++的dll

这里有2个调用法:

方法1:

QLibrary myLib("mylib");
typedef void (*MyPrototype)();
MyPrototype myFunction = (MyPrototype) myLib.resolve("mysymbol");
if (myFunction)
    myFunction();

方法2:

typedef void (*MyPrototype)();
MyPrototype myFunction =
        (MyPrototype) QLibrary::resolve("mylib", "mysymbol");
if (myFunction)
    myFunction();

 

 

 

下面是一个例子:

使用MSVC2015编译的DLL

一个加和一个减的函数:

使用Qt进行调用(这里用WinGW)

Qt代码如下:

#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QLibrary myLib("D:\\QtProject\\libraryDemo\\DLL_C_Demo");
    typedef int (*Add)(int a, int b);
    Add function = (Add)myLib.resolve("Add");
    if(function){

        qDebug() << function(10, 20);
    }

    qDebug() << "----------华丽的分割线----------";

    typedef int (*Sub)(int a, int b);
    Sub function2 = (Sub)QLibrary::resolve("D:\\QtProject\\libraryDemo\\DLL_C_Demo.dll", "Sub");
    if(function2){

        qDebug() << function2(10, 100);
    }

    return a.exec();
}

两个程序下载仓库:

https://github.com/fengfanchen/Qt/tree/master/sharedLibrariesDemo

 

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/106793918
今日推荐