回调函数,就是自己写一个函数自己不调用,而是其他程序调用,下面举例exe调用dll函数,反过来,dll也调用exe函数,模拟杀毒软件查杀调用。
exe代码:
#include <windows.h> #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; #define Log(str) {{printf("[Kill]%s ",str);}} typedef void(*pFunc)(DWORD addrFunc,char * msg); typedef bool(*pFuncScan)(); pFunc dllCallBack; pFuncScan dllScan; void showResult(char * msg) { Log(msg); } int main(int argc,char * argv[]) { HMODULE hDll = LoadLibrary("CallBackDll.dll"); if (!hDll) { Log("LoadLibrary Failed"); return 0; } dllCallBack = (pFunc)GetProcAddress(hDll, "RegCallBack"); if (!dllCallBack) { Log("GetProcAddress Failed"); return 0; } dllScan = (pFuncScan)GetProcAddress(hDll, "ScanVirus"); dllCallBack((DWORD)showResult, "Main Virus"); if (dllScan()) { Log("Main Scan OK"); } system("pause"); return 0; }
dll 代码:
#include <windows.h> #include <stdio.h> //Log Print #define Log(str) {{printf("[Kill]%s ",str);}} //Function Pointer typedef void (* pFunc)(char * argument); char * argument = NULL; pFunc callback; //Register CallBack Function extern "C" __declspec(dllexport) void RegCallBack(DWORD addrFunc,char * msg) { callback = (pFunc)addrFunc; argument = msg; } //Real Scan(Real Kill Function) bool ScanMain() { Log("Virus...."); Sleep(1000); return true; } //Scan Show extern "C" __declspec(dllexport) bool ScanVirus() { Log("Scanning Begin..."); Sleep(3000); if (ScanMain()) { callback(argument); Sleep(1000); } Log("Scanning End..."); return TRUE; } //Dll Main BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; }