一、创建目标DLL文件
DLL名称:targetdll.dll
头文件(targetdll.h):
#pragma once __declspec(dllexport) void __stdcall hello(); __declspec(dllexport) int __stdcall add(int a, int b);
源文件(targetdll.cpp)
#include <stdio.h> #include "targetdll.h" void __stdcall hello() { printf("\n--------------------------\n"); printf("\n-----------hello-------------\n"); printf("\n------------------------\n"); } int __stdcall add(int a, int b) { printf("\n------------------------\n"); printf("\n-----------add-------------%d\n", a + b); printf("\n------------------------\n"); return (a + b); }
二、DLL文件的调用:
#include <Windows.h> #include <stdio.h> #include "targetdll.h" typedef int (*ADD_FUNC)(int a, int b); int main() { HMODULE hModule = LoadLibrary(TEXT("targetdll.dll")); if (hModule == NULL) { printf("dll加载失败\n"); return 0; } FARPROC pFn = GetProcAddress(hModule, "hello"); pFn(); ADD_FUNC pAdd = (ADD_FUNC)GetProcAddress(hModule, "add"); pAdd(10, 20); FreeLibrary(hModule); system("pause"); return 1; }
输出结果:
三、创建替换DLL文件
DLL名称:replacedll.dll
转发指令:#pragma comment(linker, "/export:导出名称=被转发的dll名称.被转发的函数名称")
#include <Windows.h> #include "replacedll.h" #pragma comment(linker, "/export:hello=targetdll_old.hello") BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: OutputDebugString(TEXT("Load replacedll")); break; case DLL_THREAD_ATTACH:break; case DLL_THREAD_DETACH:break; case DLL_PROCESS_DETACH: OutputDebugString(TEXT("UnLoad replacedll")); break; } return TRUE; }
将目标文件targetdll.dll改为targetdll_old.dll;然后将替换文件replacedll.dll改成目标文件targetdll.dll,然后调用:
#include <Windows.h> #include <stdio.h> #include "targetdll.h" typedef int (*ADD_FUNC)(int a, int b); int main() { HMODULE hModule = LoadLibrary(TEXT("targetdll.dll")); if (hModule == NULL) { printf("dll加载失败\n"); return 0; } FARPROC pFn = GetProcAddress(hModule, "hello"); pFn(); //ADD_FUNC pAdd = (ADD_FUNC)GetProcAddress(hModule, "add"); //pAdd(10, 20); FreeLibrary(hModule); system("pause"); return 1; }
打印结果:
标签:include,targetdll,hModule,int,编程,dll,Win32,DLL From: https://www.cnblogs.com/TechNomad/p/17719552.html