动态链接库的简单实现(原创)

来源:互联网 发布:阿里云华北3 编辑:程序博客网 时间:2024/06/17 03:34

    昨天大概谈谈我对静态链接库很皮毛的认识。今天再来谈谈我对动态链接库更皮毛的认识。

    动态链接库是在运行过程中动态加载。其运行原理基本是这样的,操作系统加载DLL的副本到内存,然后通过操作系统获取DLL中函数入口地址。系统传入程序的参数到链接库中的函数内,获取DLL内存副本运行的返回值,从而完成程序某模块的功能。这样做的好处是显而易见的,1、扩展了应用程序的特性;2、可以用许多种编程语言来编写;3、简化了软件项目的管理;4、有助于节省内存;5、有助于资源共享。

    下面我给个简单的实例。

//dll.h

#include <windows.h>

extern "C" _declspec(dllexport) int Max(int a, int b);
extern "C" _declspec(dllexport) int Min(int a, int b);

 

// dll.cpp : Defines the entry point for the DLL application.

#include "dll.h"

BOOL APIENTRY DllMain( HANDLE hModule, DWORD  ul_reason_for_call,LPVOID lpReserved )
{
    return TRUE;
}

int Max(int a, int b){
 if(a>=b)return a;
 else return b;
}

int Min(int a, int b){
 if(a>=b)return b;
 else return a;
}

    编译-链接。生成dll.dll然后建个测试工程test,把dll.dll复制到test工程的目录中。

    新建test.cpp。

//test.cpp

#include <iostream>
#include <windows.h>
using namespace std;
typedef int (*Max)(int a,int b);
typedef int (*Min)(int a,int b);

int main()
{
 HINSTANCE hDLL;//DLL句柄
 Max nummax;
 Min nummin;
 hDLL=LoadLibrary("dll.dll");//加载动态链接库dll.dll文件
 if(!hDLL){
  cout<<"dll.dll missing!"<<endl;
  return -1;
 }
 nummax=(Max)GetProcAddress(hDLL,"Max");
 nummin=(Min)GetProcAddress(hDLL,"Min");
 cout<<"Max(8,5)="<<nummax(5,8)<<";Min(10,20)="<<nummin(10,20)<<";"<<endl;
 FreeLibrary(hDLL);//释放动态链接库
}

    运行下,就可以看到结果了。

原创粉丝点击