建立部分:
1.使用导出函数关键字_declspec(dllexport)建立:程序员
//DllTest.h extern "C" _declspec(dllexport) int Max(int a, int b); //导出声明 extern "C" _declspec(dllexport) int Min(int a, int b); //DllTest.cpp #include "DllTest.h" int Max(int a, int b) { return (a>=b)?a:b; } int Min(int a, int b) { return (a<=b)?a:b; }
2.使用模块文件(;后的一行表明注释) VS2012 没有实验成功函数
;DllTest.def
LIBRARY DllTest
EXPORTS
Max@1
Min@2spa
.def 文件的规则为:
(1)LIBRARY 语句说明.def 文件相应的 DLL;
(2)EXPORTS 语句后列出要导出函数的名称。能够在.def 文件中的导出函数名后加@n,表示要导出函数的序号为 n(在进行函数调用时,这个序号将发挥其做用);
(3).def 文件中的注释由每一个注释行开始处的分号 (;) 指定,且注释不能与语句共享一行。.net
使用部分:指针
采用隐式连接方式创建一个DLL文件,连接程序会自动生成一个与之对应的LIB导入文件。该文件包含了每个DLL导出函数的符号名和可选的标识号,可是并不含有实际的代码。LIB文件做为DLL的替代文件被编译到应用程序项目中。code
//UseDll.h 声明 #pragma comment(lib,"DllTest.lib") extern "C"_declspec(dllimport) int Max(int a,int b); //导入声明 extern "C"_declspec(dllimport) int Min(int a,int b); //UseDll.cpp #include"Dlltest.h" void main() { printf("MinValue:%d\n",min(8,10) ); }
显式连接,程序员就没必要再使用导入文件,而是直接调用Win32的LoadLibary函数,并指定DLL的路径做为参数。LoadLibary返回HINSTANCE参数,应用程序在调用GetProcAddress函数时使用这一参数。GetProcAddress函数将符号名或标识号转换为DLL内部的地址。get
#include "stdafx.h" #include <Windows.h> typedef int(*pMax)(int a,int b);//定义与动态库中的函数类型相同的指针类型 int _tmain(int argc, _TCHAR* argv[]) { pMax MaxFunc; HINSTANCE hDLL; //DLL 句柄 hDLL=LoadLibrary("TestDemo_CreateDll.Dll");//加载动态连接库文件 MaxFunc=(pMax)GetProcAddress(hDLL,"Max"); int MaxValue=MaxFunc(5,8); printf("两数最大值:%d\n",MaxValue); FreeLibrary(hDLL);//卸载Dll文件 return 0; }