动态链接库dll的 静态加载 与 动态加载

 
动态链接是指在生成可执行文件时不将所有程序用到的函数链接到一个文件,因为有许多函数在操作系统带的dll文件中,当程序运行时直接从操作系统中找。  
而静态链接就是把所有用到的函数全部链接到exe文件中。
动态链接是只建立一个引用的接口,而真正的代码和数据存放在另外的可执行模块中,在运行时再装入;  
而静态链接是把所有的代码和数据都复制到本模块中,运行时就不再需要库了。
 
 
1.生成  静态链接库 newdll)  win32项目 ->  dll

添加.h文件 
betabinlib.h

 

 

  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  
#ifndef BETABINLIB_H
#define BETABINLIB_H
 
#ifdef NEWDLL_EXPORTS   //自动添加的宏   右键工程-属性-配置属性-预处理器-..定义
#define MYDLL_API extern "C" __declspec(dllexport)
#else
#define MYDLL_API extern "C" __declspec(dllimport)
#endif
 
MYDLL_API int add(int x, int y);  // 必须加前缀
#endif


添加.cpp文件  betabinlib.cpp

 

 

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

 

编译生成  .dll 和 .(1)dll的静态加载--将整个dll文件 加载到  .exe文件中
特点:程序较大,占用内存较大,但速度较快(免去 调用函数LOAD

print?

  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. }  
#include <stdio.h>
#include "betabinlib.h"
#include <Windows.h>
#pragma comment(lib, "newdll.lib")
 
int main()
{
    printf("2 + 3 = %d \n", add(2, 3));
    return 0;
}

 

 

 

print?

    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. }  
posted @ 2017-08-22 22:19  loanhicks  阅读(355)  评论(0编辑  收藏  举报