windows核心编程(第五版)20.3节的延迟载入Dll
延迟载入Dll技术出现的原因:
因为DLL的加载是比较浪费时间的,特别是大型软件加载,因此,这项技术是在应对软件初始化过程中避免浪费太多的时间。
[1]因为部分DLL是在软件运行过程中才加载的。因此,DLL的加载延迟在了进程的运行过程中,节省程序的初始化时间。
[2]解决软件兼容性问题,比如一个新软件在老系统中运行,需要调用老版本的函数,我们只需要先使用GetVerisonEx()获得系统版本,然后再调用相应的函数,这样就解决了软件兼容性的问题,否则,新版在旧系统中就会报错。
源代码:
Resource.def
LIBRARY EXPORTS sub_1 @1
Dll.cpp
// Dll.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include <stdio.h>
#define dll extern "C" __declspec(dllexport)
#include "dll.h"
dll void __stdcall sub_1()
{
printf("Hello SH!
");
}
Dll.h
#pragma once #ifndef dll #define dll extern "C" __declspec(dllimport) #endif dll void __stdcall sub_1();
延迟载入Dll.cpp
// 延迟载入Dll.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
#include <delayimp.h>
#pragma comment(lib, "Delayimp.lib")
#include "../Dll/Dll.h"
#pragma comment(lib, "Dll")//dll.lib 要放到cpp文件下
int main()
{
if (!GetModuleHandle(L"Dll.dll"))
printf("dll.dll Not Load
");
sub_1();
__HrLoadAllImportsForDll("Dll.dll");
if (GetModuleHandle(L"Dll.dll"))
printf("Dll.dll Load
");
__FUnloadDelayLoadedDLL2("Dll.dll");
if (!GetModuleHandle(L"Dll.dll"))
printf("Dll.dll UnLoad
");
return 0;
}
相关设置:
控制台应用程序相关设置:

