一、动态链接库调用方式
参考 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);
}