全部博文(584)
分类: WINDOWS
2011-04-07 14:01:52
一、 生成DLL
1. 新建DLL工程
生成DLL可以多种方法,这里介绍一种。在VS中,新建一个空的项目,选Win32 Console Application,新建完后修改工程属性:把生成EXE改为生成DLL
2. 源代码:
view plaincopy to clipboardprint?
#include "stdafx.h"
#ifdef __cplusplus // if used by C++ code
extern "C" { // we need to export the C interface
#endif
_declspec(dllexport) void MYSUB(int x,int y,int* z)
{
*z = x - y;
}
#ifdef __cplusplus
}
#endif
#include "stdafx.h"
#ifdef __cplusplus // if used by C++ code
extern "C" { // we need to export the C interface
#endif
_declspec(dllexport) void MYSUB(int x,int y,int* z)
{
*z = x - y;
}
#ifdef __cplusplus
}
#endif
3. 编译连接,生成xyz.dll文件
二、使用DLL
1. 新建工程
Qt Creator中创建一个新的GUI Application,在窗体上左边放置一个Label右边放置两个PushButton(Load和Quit)。
用Quit的Clicked()信号绑定close()槽,Load的Clicked()信号绑定Load()槽。
2. 源代码:
view plaincopy to clipboardprint?
void MainWindow::Load()
{
int a=1,b=2,c=6;
typedef void (*myfun)(int,int,int *);
QLibrary lib("xyz");
QString qss;
if(lib.load())
{
myfun fun1 = (myfun)lib.resolve("MYSUB");//用resolve来解析fun1函数
if ( fun1 )//解析成功则进行运算并提示相关信息
{
fun1(a,b,&c);
qss = tr("dll success load!\n 1+2=")+QString::number(c,10);
}
}
else
{
qss = tr("Not found dll!");
}
ui->label->setText(qss);
}
void MainWindow::Load()
{
int a=1,b=2,c=6;
typedef void (*myfun)(int,int,int *);
QLibrary lib("xyz");
QString qss;
if(lib.load())
{
myfun fun1 = (myfun)lib.resolve("MYSUB");//用resolve来解析fun1函数
if ( fun1 )//解析成功则进行运算并提示相关信息
{
fun1(a,b,&c);
qss = tr("dll success load!\n 1+2=")+QString::number(c,10);
}
}
else
{
qss = tr("Not found dll!");
}
ui->label->setText(qss);
}
ps:Qt帮助文档中有这么一段说明
void * QLibrary::resolve(const char* symbol)
The symbol must be exported as a C function from the library. This means that the function must be wrapped in an extern "C" if the library is compiled with a C++ compiler. On Windows you must also explicitly export the function from the DLL using the_declspec(dllexport) compiler directive, for example:
对于_declspec的说明参看 http://blog.csdn.net/lw02nju/archive/2009/07/22/4370002.aspx
extern "C" MY_EXPORT int avg(int a, int b)
{
return (a + b) / 2;
}with MY_EXPORT defined as
#ifdef Q_WS_WIN
#define MY_EXPORT __declspec(dllexport)
#else
#define MY_EXPORT
#endif