DLL中的回调函数实现
DLL文件中存放的是各类程序的函数实现过程,当程序需要调用函数时需要先载入DLL,然后取得函数地址,最后进行调用。但是有时候我们需要DLL和程序进行通信,将应用程序的某些功能提供给DLL使用,这时就可以使用回调函数。
比如应用程序A调用动态链接库D,同时需要将D中的一些日志信息反馈给A进行处理。这时可以在A中设置写日志的回调函数提供给DLL。
一、调用程序中操作
应用程序提供给DLL调用的函数
#pragma once class Mylog { public: Mylog(); ~Mylog(); static void writelog(const char *plogFile, int p_nType, const char * logText); }; #include "stdafx.h" #include "Mylog.h" Mylog::Mylog() { } Mylog::~Mylog() { } void Mylog::writelog(const char *plogFile, int p_nType, const char * logText) { OutputDebugString(__T("xcyk----you can do what you want to do----xcyk")); }
定义一个回调函数的原型,也就是提供给DLL中调用的函数。最后需要将这个函数地址传递给DLL中使用
typedef void(*writeLog)(const char *plogFile, int p_nType, const char * logText);
定义了一个函数指针writeLog,这个函数里面有三个参数,返回值为void。
应用程序中需要调用DLL提供的函数将回调函数传递出去。假设这个函数是mytestfun
mytestfun((writeLog *)(Mylog::writelog));
方法二:
#define MYTESTFUN "mytestfun"
typedef void(*SetLog)(writeLog *pFun);
//方法一:
HMODULE hModelHand = LoadLibrary(__T("MyDLL.DLL"));
SetLog pLogShowFun = (SetLog)GetProcAddress(hModelHand, MYTESTFUN);
{
if (NULL == pLogShowFun)
AfxMessageBox(__T("get mydll.dll address erro!"));
}
pLogShowFun((writeLog *)(Mylog::writelog));
二、DLL中操作
#define MyDLL_API extern "C" __declspec( dllexport )
typedef void(*writeLog)(const char *plogFile, int p_nType, const char * logText);
writeLog g_RunLog = NULL;
MyDLL_API void mytestfun(void *pfun)
{
if (pfun)
{
g_RunLog = (writeLog)pfun;
}
}