ITeye博客

qt 动态链接库dll

openstudy · 2011-01-07 17:00 · 编程语言 · Markdown

用Qt生成dll类库及调用方法 (http://hi.baidu.com/bianxuehui/blog/item/17fce3efa5ba02222cf5343e.html) 使一个项目编译生成DLL库而不生成可执行文件: 1.删除main()方法; 2.qmake -project 将.pro项目文件中的TEMPLATE = app改为TEMPLATE = lib。(lib必须大小写匹配) 3.qmake 4.make 然后编译,此时生成的就是.a和.dll的文件。


在另一个项目中调用此DLL:

在项目文件中添加LIB。如添加此行:LIBS += "D:\workspace\MRP_Common\debug\common.dll" (common.dll既是上面生成的DLL); 复制dll中类或方法的头文件到该项目中,并在要调用common.dll中类或方法的文件上面include; make,在debug目录中生成可执行文件,然后将dll复制到debug中,运行。


Qt: 生成最简单的dll示例(http://www.cppblog.com/biao/archive/2009/08/29/94712.html) ########################### 生成DLL的工程: #######################

修改pro文件: TEMPLATE=lib ########################### .h文件 ####################### #ifndef DLLTEST_H #define DLLTEST_H

#ifdef Q_WS_WIN

#define MY_EXPORT __declspec(dllexport)

#else

#define MY_EXPORT

#endif

class DllTest { public: DllTest(); int getAge() { return 10; } };

extern "C" MY_EXPORT int add(int a, int b) { return a + b; }

extern "C" MY_EXPORT DllTest* getDllTest(); // 使用类

#endif // DLLTEST_H

########################### .cpp文件 ####################### #include "dlltest.h" #include

DllTest::DllTest() { qDebug() << "Shared Dll Test"; }

DllTest* getDllTest() { return new DllTest(); }

// 如果是C++编译的函数, 要使用extern "C"来包装成C函数(导出函数, 给外部提供服务).

########################### 使用DLL的工程: ####################### pro文件中加入: LIBS += "DllTest.dll"

########################### 测试.cpp文件 ####################### #include "dlltest.h"

#include #include #include

typedef int (*AddFunc)(int, int);

typedef DllTest* (*GetFunc)();

int main(int argc, char* argv) { QApplication app(argc, argv, false); QLibrary lib("DllTest"); if (lib.load()) { qDebug() << "Load dll successfully."; AddFunc func = (AddFunc)lib.resolve("add"); if (func) { qDebug() << func(1, 3); }

    GetFunc g = (GetFunc)lib.resolve("getDllTest");
    if (g) {
        DllTest *t = g(); // 使用DLL中的类
        qDebug() << t->getAge();
        delete t;
    }

} else {
    qDebug() << "Load dll Failed";
}

return app.exec();

}

http://hi.baidu.com/kxw102/blog/item/9aed4be877cef631b90e2db8.html有描述dll显式调用和隐式调用的描述

就我目前的知识来讲,我个人觉得用QPluginLoader加载dll比较方便

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。