在vc6中,新建一个Win32 Dynamic-Link Library Project.
命名为:dllexample。然后看下面的例子。
下面是dllexample.cpp:
//===================================
#include "stdafx.h"
/*
* dll文件的输出函数声明
*/
extern "C" _declspec(dllexport) float t_max(float x, float y);
extern "C" _declspec(dllexport) float t_min(float x, float y);
/*
* DllMain函数
* 进程初始化和终止时都要调用此函数
* 在这里可以分配和释放资源
* 关于DllMain函数的详细情况这里先不讨论
*/
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
/*
* dll的输出函数定义,这里以简单的取大取小运算为例
*/
float t_max(float x, float y)
{
return x > y ? x : y;
}
float t_min(float x, float y)
{
return x < y ? x : y;
}
//=================================
build一下。生成两个文件:dllexample.dll和dllexample.lib
那么如何调用呢?
有两种方法:
方法一:隐式链接
1.新建win32 工程。命名为testdll.
2.把上面生成的dllexample.lib和dllexample.dll拷贝到testdll工程目录下。
3.在Project-settings-link-Objcte/Lib中加入dllexample.lib
4.在testdll.cpp添加代码如下:
//============================
// testdll.cpp //
#include "stdafx.h"
#include "stdio.h"
/* 在合适的地方声明dll中的函数原型 */
float t_max(float x, float y);
float t_min(float x, float y);
int main(int argc, char* argv[])
{
float x = (float)3.6, y = (float)9.8;
float fmax = t_max(x, y);
float fmin = t_min(x, y);
printf("%f, %f", fmax, fmin);
return 0;
}
//============================
build and run。输出:
9.800000, 3.600000
方法二:显式链接
本方法适合于只有dll文件没有lib文件的情况。
1.新建win32工程testdll
2.把dllexample.dll拷贝到testdll工程目录下
3.testdll.cpp代码修改如下:
//============================
// testdll.cpp //
#include "stdafx.h"
#include "stdio.h"
#include <afxwin.h> // for HINSTANCE
int main(int argc, char* argv[])
{
float x = (float)3.6, y = (float)9.8;
//函数指针定义
typedef float(*p_fun)(float x,float y);
p_fun t_max, t_min;
//加载dll
HINSTANCE hDll = LoadLibrary("dllexample.dll");
if(hDll == NULL) return 0;
//获取函数指针
t_max = (p_fun)GetProcAddress(hDll,"t_max");
t_min = (p_fun)GetProcAddress(hDll,"t_min");
//调用
float fmax = t_max(x, y);
float fmin = t_min(x, y);
printf("%f, %f", fmax, fmin);
//释放dll
FreeLibrary(hDll);
return 0;
}
//===========================
build and run。输出:
9.800000, 3.600000
/*=====================*/
本文适合初用dll者。
好了,今天就是这样,有事下回再说!
本文介绍了在VC6中创建Win32动态链接库(DLL)的方法,以dllexample为例给出代码并生成dll和lib文件。同时阐述了调用DLL的两种方法:隐式链接和显式链接,分别给出详细步骤和代码示例,适合初次使用DLL的开发者。
941

被折叠的 条评论
为什么被折叠?



