Qt將接口文件製作成dll動態鏈接庫

第一步:新建"Qt Library“項目,刪除”XXX_global.h“文件,頭文件按照如下方式書寫
// interfacedll.h 
#ifndef INTERFACEDLL_H
#define INTERFACEDLL_H
#include <QtPlugin>
#ifdef INTERFACEDLL_LIB
# define INTERFACEDLL_EXPORT Q_DECL_EXPORT
#else
# define INTERFACEDLL_EXPORT Q_DECL_IMPORT
#endif
class INTERFACEDLL_EXPORT InterfaceDll
{
public:
InterfaceDll();
virtual ~InterfaceDll();
int add(int a,int b);
virtual int subInt(int a,int b)=0;
virtual int muitiplyInt(int a,int b)=0;
virtual double devideInt(int a,int b)=0;
};
Q_DECLARE_INTERFACE(InterfaceDll,"com.interfaceDlltest/1.0")
#endif // INTERFACEDLL_H
// interfacedll.cpp

#include "interfacedll.h"
InterfaceDll::InterfaceDll(){}
InterfaceDll::~InterfaceDll(){}
int InterfaceDll::add(int a,int b){ return a+b; }

第二步:新建"Qt Library“項目, 這個項目主要是插件的實現文件
注意由於接口類爲dll類型文件,故需要在該項目引用該dll文件

方法一:右擊“項目”—>屬性—>鏈接器—>常規—>附加庫目錄

         輸入dll文件所在的目錄

然後在“輸入”—>附加依賴項,輸入與dll對應的lib文件

VS2010有時會出現錯誤)

方法二:#pragma comment(lib , "lib文件的路徑名")

// plugindll.h

#ifndef PLUGINDLL_H
#define PLUGINDLL_H

#include <QtPlugin>
#include "interfacedll.h"
#include <qglobal.h>
#ifdef PLUGINDLL_LIB
# define PLUGINDLL_EXPORT Q_DECL_EXPORT
#else
# define PLUGINDLL_EXPORT Q_DECL_IMPORT
#endif

class PLUGINDLL_EXPORT Plugindll:public QObject,public InterfaceDll
{
Q_OBJECT
Q_INTERFACES(InterfaceDll)
public:
Plugindll();
~Plugindll();
int subInt(int a,int b);
int muitiplyInt(int a,int b);
double devideInt(int a,int b);
private:

};
#endif // PLUGINDLL_H

// plugindll.cpp

#include "plugindll.h"
Plugindll::Plugindll(){}
Plugindll::~Plugindll(){}
int Plugindll::subInt(int a,int b) { return a-b;}
int Plugindll::muitiplyInt(int a,int b) { return a*b;}
double Plugindll::devideInt(int a,int b){ return a/(b+0.0);}
Q_EXPORT_PLUGIN2(plugindll,Plugindll)

第三步:使用該接口以及插件

#pragma comment(lib , "../Win32/debug/InterfaceDll.lib")//引入動態鏈接庫
#include <QtCore/QCoreApplication>
#include "interfacedll.h"//需要使用該頭文件才能調用相應的頭文件
#include <QPluginLoader>
#include <QObject>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QPluginLoader loader("../Win32/debug/Plugindll.dll");
QObject *object=loader.instance();
InterfaceDll *interface=qobject_cast<InterfaceDll *>(object);
if (interface)
{
cout<<interface->add(10,20)<<endl;
cout<<interface->subInt(10,20)<<endl;
cout<<interface->muitiplyInt(10,20)<<endl;
cout<<interface->devideInt(10,20)<<endl;
}
return a.exec();
}

至此,順利將接口文件製作成動態鏈接庫文件,並完成相應的調用。
附測試結果如下:
Qt將接口文件製作成dll動態鏈接庫 - weyresearch - weyresearch的博客
 由於本人並非軟件相關專業出身,有些用詞不恰當還請見諒,哈哈
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章