逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::

########################### 生成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 <qDebug>


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 <QLibrary>

#include <qDebug>

#include <QApplication>


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();

}


posted on 2009-08-29 00:25 逛奔的蜗牛 阅读(4074) 评论(1)  编辑 收藏 引用 所属分类: C/C++Qt

评论

# re: Qt: 生成最简单的dll示例 2009-11-13 20:49 sdink
能不能在写清楚一点,,,,最近在网上找了很多。。便是都不能用。。。。  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理