Qt 使用QPluginLoader 加載外部dll的方法筆記


  1. 項目的一個需求是提供一個dll文件給其他 可執行文件調用。借這個機會也正好可以解決我之前一個在線升級使用更新dl方法l的思路。

在此記錄一下。各位大神如果有其他方法和思路歡迎一起探討或者賜教。。



dll 調用接口 :

  1. class IUIPLUGINBASE  
  2. {  
  3. public:  
  4.     //初始化 失敗返回-1  
  5. //    virtual int init() = 0;  
  6.     //input:顯示的起始位置x , y 軸座標  
  7.     virtual int show(int pos_x , int pos_y = 0) = 0;  
  8.   
  9. };  
  10. Q_DECLARE_INTERFACE(IUIPLUGINBASE,"uiplugins/1.0"//這個宏用聲明接口

上面代碼定義其他程序調用的接口,在這個裏面使用一個show的虛函數。 至於virtual  虛函數,展開描述,估計夠一章內容的。此處不深探究。


dll 實現的頭文件:

  1. #include <QWidget>  
  2. #include "iuipluginbase.h"  
  3. class MainDlg : public QWidget,public IUIPLUGINBASE  
  4. {  
  5.     Q_OBJECT  
  6.     Q_INTERFACES(IUIPLUGINBASE)


  1. public:  
  2.     explicit MainDlg(QWidget *parent = 0);  
  3.     ~MainDlg();  
  4.     //input:顯示的起始位置x , y 軸座標  
  5.     int show(int pos_x , int pos_y);  
  6. private slots:  
  7.   
  8. private:  
  9.   
  10. };  

dll實現類
  1. MainDlg::MainDlg(QWidget *parent) :  
  2.     QWidget(parent),  
  3.     ui(new Ui::MainDlg)  
  4. {  
  5.      
  6. }  
  7.   
  8. int MainDlg::show(int pos_x, int pos_y)  
  9. {  
  10.     move(pos_x,pos_y);  
  11.     QWidget::show();  
  12.     return 1;  
  13. }  
  14.   
  15. QT_BEGIN_NAMESPACE  
  16. Q_EXPORT_PLUGIN2(MainDlg, MainDlg)  
  17. QT_END_NAMESPACE

標紅的地方需要特別注意。



調用dll文件的地方加入代碼:

  1. QPluginLoader loader("uiplugins.dll");  
  2. IUIPLUGINBASE * P_plug;  
  3. QObject*  loaderplugin= loader.instance();  
  4. if(!loader.isLoaded())  
  5.     qDebug() << loader.errorString();  
  6. if (loaderplugin) {  
  7.     P_plug = qobject_cast<IUIPLUGINBASE * >(loaderplugin);  
  8.   
  9.     P_plug->show(100,100);  
  10. }  


通過上訴代碼段,即可實現外部程序調用dll文件。 這個功能還是非常重要的,非常適合多人開發或者在線更新,甚至插件式開發思路。

做個筆記。。有更好思路的大牛們歡迎留下您的建議。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章