天天看點

QT調用動态連結庫執行個體一、動态連結庫調用方式二、QT 5.0調用CVI生成的動态連結庫執行個體

一、動态連結庫調用方式

參考 http://blog.csdn.net/crich_moon/article/details/6039939

1、動态調用 Run-time Dynamic Linking

動态調用主要通過API函數(Window LoadLibrary、GetProcAddress、FressLibrary)來調用程式運作後需要的DLL函數,節省記憶體空間。QT中,則主要通過QLibrary進行動态加載(适用于跨平台)。

2、靜态調用 Load-time Dynamic Linking

靜态調用前提是在編譯之前已經明确知道調用DLL中的哪些函數,需要lib和相應的導入頭檔案*.h。編譯時,在目标檔案中隻保留必要的連結資訊,而不含DLL函數的代碼;當程式執行時,利用連結資訊加載DLL函數代碼并在記憶體中将其連接配接入調用程式的執行空間中,其主要目的是便于代碼共享。

二、QT 5.0調用CVI生成的動态連結庫執行個體

1、CVI生成動态連結庫

CVI是個很強大的開發工具

建立過程參考

http://wenku.baidu.com/link?url=hvST1qn3UTjIYvLimf2cSDovK5YCagHU--WjRKOqXlYplBV-MXEGS-jqikiZlnRTNh3GM4efyFy_GSqGC26QMZWN5UUBkUSmeV3uJPXrBj3

代碼dll1.h和dll1.c
#ifndef __dll1_H__
#define __dll1_H__

#include "cvidef.h"
int __stdcall Add(int, int);

#endif  /* ndef __dll1_H__ */
           
#include <cvirte.h>
#include "dll1.h"

int __stdcall DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
	switch (fdwReason)
	{
		case DLL_PROCESS_ATTACH:
			if (InitCVIRTE (hinstDLL, 0, 0) == 0)
				return 0;	  /* out of memory */
			break;
		case DLL_PROCESS_DETACH:
			CloseCVIRTE ();
			break;
	}
	
	return 1;
}

int __stdcall DllEntryPoint (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
	/* Included for compatibility with Borland */

	return DllMain (hinstDLL, fdwReason, lpvReserved);
}

/*extern "C" */int __stdcall Add(int x, int y)
{
	return x+y;
}
           

2、QT動态連結庫的調用

2.1 動态調用

#include "mydlg.h"
#include "ui_mydlg.h"
#include "qmessagebox.h"
#include <QLibrary>

MyDlg::MyDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MyDlg)
{
    ui->setupUi(this);

}

MyDlg::~MyDlg()
{
    delete ui;
}

void MyDlg::on_pushButton_clicked()
{
     int a = 10;
     int b = 11;
     int c = 0;
     typedef int (*myfun)(int ,int);
     QLibrary hdll("dll1.dll");
     if(hdll.load())
     {
         QMessageBox::about(this, "Msg","Load Success!");
         myfun fun1 = (myfun)hdll.resolve("Add");
         if(fun1)
         {
             c = fun1(a, b);
             QString result_msg = tr("dll加載成功!")+QString::number(c,10);
             QMessageBox::about(this, "Result", "The Sum is "+result_msg);

         }
         hdll.unload();
     }
}
           

2.2 靜态調用

參考http://hi.baidu.com/ayuyuan/item/756788382b4c95573075a1c6 在XX.pro中添加: LIBS += ./debug/dll1.lib

建立并添加頭檔案:dll2.h

//dll2.h
#ifndef DLL2_H
#define DLL2_H
//#pragma comment(lib, "dll1.lib")

extern "C" __declspec(dllimport) int __stdcall Add(int, int);
#endif // DLL1_H







//myDlg.cpp中直接使用DLL函數
void MyDlg::on_pushButton_clicked()
{
     int a = 10;
     int b = 11;
     int c = 0;

     c = Add(a, b);
     QString result_msg = tr("dll加載成功!")+QString::number(c,10);
     QMessageBox::about(this, "Result", "The Sum is "+result_msg);

}