本篇博文是基于:
/qq78442761/article/details/8937
这篇博文的代码!
这里主要是做两个补充!
1. 模块一想加入一个处理,输出I am fine, fuck you1!
2. 只执行write模块!
这里修改上次的代码!
程序运行截图如下:
程序结构如下:
源码如下:
FirstModule.h
#pragma once#include "stdef.h"#include "moduleAdmin.h"int InitFirstModule();
moduleAdmin.h
#pragma once#include "stdef.h"typedef enum tagMODULE_SETS//SETS表示这是枚举集合{MY_ALL_MODULE = 0,MY_READ_MODULE = 1,MY_WRITE_MODULE = 2,MY_INVALID_MODULE = 0xffff}MODULE_SETS_E;//E表示enumtypedef int(*pProcFun)();typedef struct tagMoudleData//一般带有管理的结构体在C语言中都是tagXXXX{int iModule;//每个模块唯一IDpProcFun pFun;}MOUDLE_DATA_S;//一般在结构体结尾都加S,代表struct;int RegisterProc(int iModule, pProcFun pFun);int ExcuteAllModule();int ExcuteWriteModule();
SecondModule.h
#pragma once#include "stdef.h"#include "moduleAdmin.h"int InitSecondModule();
stdef.h
#pragma once#include <stdio.h>#include <Windows.h>#define OK 0#define ERR -1
FirstModule.cpp
#include "FirstModule.h"//模块一想加一个处理,输出I am fine, fuck you!int iFlag = 2;int FirstModuleEx(){printf("I am fine, fuck you!\n");return OK;}int FirstModuleProc(){printf("Hello I am First Module\n");if(iFlag <= 0){FirstModuleEx();}iFlag--;return OK;}int InitFirstModule(){RegisterProc(MY_WRITE_MODULE, FirstModuleProc);return OK;}
main.cpp
#include "stdef.h"#include "FirstModule.h"#include "SecondModule.h"DWORD WINAPI MyThread(){while(1){printf(">");ExcuteAllModule();Sleep(1000);}}DWORD WINAPI MyThreadEx(){while(1){printf("#");ExcuteWriteModule();Sleep(1000);}}int TestFunPtr(){InitFirstModule();HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread, NULL, 0, NULL);HANDLE hThreadEx = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThreadEx, NULL, 0, NULL);Sleep(3000);InitSecondModule();Sleep(3000);TerminateThread(hThread, 0);CloseHandle(hThread);TerminateThread(hThreadEx, 0);CloseHandle(hThreadEx);return OK;}int main(int argc, int *argv[]){TestFunPtr();getchar();return 0;}
moduleAdmin.cpp
#include "moduleAdmin.h"#define MAX_PROC 100int g_iProCnt = 0;//全局的前面加一个gMOUDLE_DATA_S FunList[MAX_PROC] = {0};int RegisterProc(int iModule, pProcFun pFun){if(g_iProCnt == MAX_PROC){return ERR;}FunList[g_iProCnt].iModule = iModule;FunList[g_iProCnt].pFun = pFun;g_iProCnt++;return OK;}//调用注册的函数int ExcuteAllModule(){for(int i = 0; i < g_iProCnt; i++){FunList[i].pFun();}return OK;}//只运行写模块int ExcuteWriteModule(){for(int i = 0; i < g_iProCnt; i++){if(FunList[i].iModule == MY_WRITE_MODULE){FunList[i].pFun();}}return OK;}
SecondModule.cpp
#include "SecondModule.h"int SecondModuleProc(){printf("Hello I am Second Module\n");return OK;}int InitSecondModule(){RegisterProc(MY_READ_MODULE, SecondModuleProc);return OK;}
源码打包下载地址:
/fengfanchen/CAndCPP/tree/master/CfunctionPtrAndCallBack%20supplement