DLL的静态加载和动态加载

来源:互联网 发布:战龙三国许褚进阶数据 编辑:程序博客网 时间:2024/05/21 14:40
原文章地址:http://blog.csdn.net/youxin2012/article/details/11538491(有改动)
DLL 两种加载方式  :动态加载静态加载

静态加载是指在运行程序之前由操作系统的加载器将DLL和EXE一起加载到内存里。注意这里与程序的静态链接区别开来,静态链接发生在编译过程之中,而DLL的静态加载是发生在程序运行之前
动态加载是指在程序运行过程中程序自己完成对DLL的加载,主要用到LoadLibrary(加载DLL)、GetProcAddress(获得DLL中API函数的地址)FreeLibrary(释放DLL)。我个人认为DLL的动态加载类似于读写文件,只不过文件时被读入文件流中,而DLL中的数据和代码是被读入到相应的数据区和代码区中

1.生成  静态链接库(导入库:用于在 DLL 中找到 API 的入口) lib 和动态链接库 dll
 
新建工程 (newdll)  win32项目 ->  dll
添加.h文件 
betabinlib.h

[cpp] view plaincopy
  1. #ifndef BETABINLIB_H  
  2. #define BETABINLIB_H  
  3.    
  4. #ifdef NEWDLL_EXPORTS   //自动添加的宏   右键工程-属性-配置属性-预处理器-..定义  
  5. #define MYDLL_API extern "C" __declspec(dllexport)  
  6. #else  
  7. #define MYDLL_API extern "C" __declspec(dllimport)  
  8. #endif  
  9.    
  10. MYDLL_API int add(int x, int y);  // 必须加前缀  
  11. #endif  

添加.cpp文件  betabinlib.cpp

[cpp] view plaincopy
  1. #include "stdafx.h"  
  2. #include "betabinlib.h"  
  3.    
  4. int add(int x, int y)  
  5. {  
  6.     return x + y;  
  7. }  

编译生成  .dll 和 .lib(导入库)文件
 
2.使用

(1)dll的静态加载--将整个dll文件 加载到  .exe文件中
特点:程序较大,占用内存较大,但速度较快(免去 调用函数LOADLIB等)
测试:
需要  .lib  和 .dll两个文件     (.lib 做 引导用),.h文件

main.cpp

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include "betabinlib.h"  
  3. #include <Windows.h>  
  4. #pragma comment(lib, "newdll.lib")  
  5.    
  6. int main()  
  7. {  
  8.     printf("2 + 3 = %d \n", add(2, 3));  
  9.     return 0;  
  10. }  

(2) dll的动态加载--根据需要加载响应函数,随时可卸载。不会因为找不到dll, 导致程序不能运行(需要自己做判断处理)。

只需要 .lib文件,不需要 .h文件

main.cpp
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <Windows.h>  
  3.    
  4. int main()  
  5. {  
  6.     HINSTANCE h=LoadLibraryA("newdll.dll");  
  7.     typedef int (* FunPtr)(int a,int b);//定义函数指针  
  8.    
  9.     if(h == NULL)  
  10.     {  
  11.     FreeLibrary(h);  
  12.     printf("load lib error\n");  
  13.     }  
  14.     else  
  15.     {  
  16.         FunPtr funPtr = (FunPtr)GetProcAddress(h,"add");  
  17.         if(funPtr != NULL)  
  18.         {  
  19.             int result = funPtr(3, 3);  
  20.             printf("3 + 3 = %d \n", result);  
  21.         }  
  22.         else  
  23.         {  
  24.             printf("get process error\n");  
  25.             printf("%d",GetLastError());  
  26.         }  
  27.         FreeLibrary(h);  
  28.     }  
  29.    
  30.     return 0;  
  31. }  
0 0