关键字:DLL, 回调函数, 导出函数, 导入函数, 线程, DLL中定时器实现, 消息队列等。 #ifndef DLLEXPORT_H #define DLLEXPORT_H typedef void (*PFUN)(void); #ifdef __cplusplus extern "C" { #endif #ifndef DLLQQAPI #define DLLQQAPI __declspec(dllexport) #else #define DLLQQAPI __declspec(dllimport) #endif DLLQQAPI int add(int a, int b); DLLQQAPI bool MainSetFun(PFUN pFun); DLLQQAPI int subtract(int a, int b); #ifdef __cplusplus } #endif #endif 定义导出函数头文件 #define DLLQQAPI __declspec(dllexport) #include "stdafx.h" #include "DLLExport.h" #include "Ccls.h" int add(int a, int b) { return a + b; } bool MainSetFun(PFUN pFun) { if (g_cls == NULL) { g_cls = new Ccls(); } if (g_cls != NULL) { g_cls->SetFun(pFun); //g_cls->call(); return true; } return false; } int subtract(int a, int b) { return a - b; } 定义导出函数源文件 #pragma once #include "DLLExport.h" class Ccls { public: Ccls(void); virtual ~Ccls(void); public: bool SetFun(PFUN pfun); static void CALLBACK TIMERFUN( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime ); static void threadfun(void *); void call(); public: static PFUN pFunProc; static UINT_PTR m_nTimerId; }; extern Ccls *g_cls; #include "StdAfx.h" #include "Ccls.h" #include <process.h> Ccls *g_cls = NULL; PFUN Ccls::pFunProc = NULL; UINT_PTR Ccls::m_nTimerId = 0; Ccls::Ccls(void) { _beginthread(threadfun, 0, NULL); } Ccls::~Ccls(void) { } bool Ccls::SetFun(PFUN pfun) { pFunProc = pfun; return true; } void CALLBACK Ccls::TIMERFUN(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime ) { Ccls::pFunProc(); } void Ccls::call() { for (int i = 0; i < 6; i++) { Ccls::pFunProc(); } } void Ccls::threadfun(void *) { m_nTimerId = ::SetTimer(NULL, 1, 500, TIMERFUN); MSG msg; while (GetMessage(&msg, // message structure NULL, // handle to window to receive the message 0, // lowest message to examine 0)) // highest message to examine { TranslateMessage(&msg); // translates virtual-key codes DispatchMessage(&msg); // dispatches message to window } } 定义主要操作类,在DLL中定义。 // CallBackFun.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "../dll/DLLExport.h" #include <iostream> #include <conio.h> using std::cout; using std::endl; //function pointer typedef int (*PFCALLBACK)(int param1, int param2); #pragma comment(lib, "DLL.lib") //declare function int CBFun1(int param1, int param2) { int sum = param1 + param2; cout << "CBFun1 is " << sum << endl; return sum; } int CBFun2(int par1, int par2) { int sum = par1 * par2; cout << "CBFun2 is " << sum << endl; return sum; } void callfun() { for (int i = 1; i < 50; i++) { //CBFun1(i, i); CBFun2(i, i); } } void callfuntion() { static int i = 0; if (i % 10 == 0) { cout << endl; } cout << ++i << " "; } int _tmain(int argc, _TCHAR* argv[]) { //callfun(); cout << add(88, 9) << endl; MainSetFun((PFUN)callfuntion); cout << subtract(88, 9) << endl; getch(); return 0; } 测试程序。