步骤1:
打开VS2005软件,创建DLL工程。工程命名test.
点击下一步,应用程序类型为DLL,空工程。
完成,一个新的DLL工程设置完毕,接下来编辑源码
步骤2:
添加头文件,命名为test.h,编辑内容:
#ifndef TEST_H
#define TEST _H //防止重复定义
#endif
#include <stdio.h> //头文件引用
#if defined DLL_EXPORT //源文件需引用下一函数
#define DECLDIR __declspec(dllexport)//就是这个
#else
#define DECLDIR __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
DECLDIR int add(int a, int b); //函数声明
DECLDIR void function(void);
#endif
解释:VC中有两种方式导出DLL文件中的函数
使用 __declspec关键字。
创建模板定义文件(Module_Definithion File)即.def文件。
在此使用第一种方法:
_declspec(dllexport)作用是导出函数符号到DLL的一个存储类中。在头文件中定义#define DECLDIR __declspec(dllexport)宏来运行这个函数。
使用条件编译,在源文件中宏定义 #define DLL_EXPORT 来运行这个函数。
//******************************************************************************
步骤3:
创建源文件 test.c
#include <stdio.h>
#define DLL_EXPORT
#include "test.h"
#ifdef __cplusplus
extern "C" {
#endif
//定义Dll中的所有函数
DECLDIR int add(int a, int b)
{
return a+b;
}
DECLDIR void function(void)
{
printf("DLL called\n");
}
编译工程,生成test.dll文件和test.lib文件(注:找到工程目录,这两个文件在外面的debug文件夹下)。
点击“生成”即可。
1、 动态库的调用
使用创建好的DLL库文件,创建一个控制台应用程序
隐式链接
连接到.lib文件,首先将test.h头文件,test.dll动态库文件,test.lib静态库文件放在控制台应用程序工程的目录中,即源文件所在的文件夹里。
在使用动态库时,在C文件的开头需要加入:
#pragma comment(lib," test.lib")//链接.lib文件
//导入需要是要使用的函数,而这些函数则是在创建动态库时所生命导出的函数
_declspec(dllimport) int add(int a, int b);
_declspec(dllimport) void function(void);
添加源文件test1.cpp,编码:
#include <stdio.h>
#pragma comment(lib," test.lib")//链接.lib文件
_declspec(dllimport) int add(int a, int b);
_declspec(dllimport) void function(void);
int main()
{
function();
printf(“%d”,add(25,25))
return 0;
}
最后显示结果:
//******************************************************************************
显式链接
只加载.dll文件,但需用到函数指针和Windows 函数,不需要.lib文件和.h头文件。
#include <stdio.h>
#include <windows.h>
typedef int (*AddFunc)(int, int);
typedef void (*FunctionFunc)(void);//函数指针
int main()
{
AddFunc _AddFunc;
FunctionFunc _FunctionFunc;
//HINSTANCE实例句柄(即一个历程的入口地址)
HINSTANCE hInstLibrary = LoadLibraryA("ceshi1.dll");
//注意,此时的LoadLibraryA()窄字符集和LoadLibraryW()宽字符集的区别,后有介绍。
if(hInstLibrary == NULL)
{
FreeLibrary(hInstLibrary);//释放DLL获得的内存,若句柄无效
}
//获得函数的入口地址,还需类型转换
_AddFunc = (AddFunc)GetProcAddress(hInstLibrary,"add");
_FunctionFunc = (FunctionFunc)GetProcAddress(hInstLibrary,"function");
if(_AddFunc==NULL || _FunctionFunc ==NULL)//确定是否成功。
{
FreeLibrary(hInstLibrary);
}
Printf(“%d”,AddFunc(25,25));
_FunctionFunc();
FreeLibrary(hInstLibrary);
return 0;
}