Visual C++ 回调函数示例

来源:互联网 发布:labtool48uxp软件下载 编辑:程序博客网 时间:2024/06/06 06:53

设想你的应用需要加载一个 DLL 库,这个 DLL 可能是你自己开发的或者是第三方的,而且你的应用依赖该 DLL 来获取一些数据。大多数 DLL 都提供了 APIs 用于执行特定的函数并返回相应值。

调用 DLL 的 API 过程是比较占用资源的,你可能需要增加额外的效果来运行某些调度器。此外,无效的返回数据导致无法保证 API 返回正确的值。

为了降低负载,我们可以创建一个回调函数,并注册到 DLL 中。在这个例子中,我们不需要创建调度器来定期调用 DLL 的 API。而是 DLL 在需要的时候调用回调函数并在数据有效时触发应用程序。

该教程将告诉你如何创建一个回调函数并注册到 DLL 中。

Visual C++ Callback Function Example

解决方案
  1. 创建一个 Win32 控制台应用项目,名称为 “SampleCallback”. 请确认是控制台类型的应用项目
  2. 添加一个新的 Win32 应用项目到同一个解决方案中,名为  “callbackproc”. 确认应用项目类型是 DLL

    Visual C++ Callback Function Example
    callbackproc 项目
  3. 打开 callbackproc.h 文件,并输入下列代码:
    01#include <string>
    02  
    03#ifdef CALLBACKPROC_EXPORTS
    04#define CALLBACKPROC_API __declspec(dllexport)
    05#else
    06#define CALLBACKPROC_API __declspec(dllimport)
    07#endif
    08  
    09// our sample callback will only take 1 string parameter
    10typedef void (CALLBACK * fnCallBackFunc)(std::string value);
    11  
    12// marked as extern "C" to avoid name mangling issue
    13extern "C"
    14{
    15    //this is the export function for subscriber to register the callback function
    16    CALLBACKPROC_APIvoid Register_Callback(fnCallBackFunc func);
    17}
  4. 打开 callbackproc.cpp 文件并输入下列代码
    01#include "stdafx.h"
    02#include "callbackproc.h"
    03#include <sstream>
    04  
    05// This is an example of an exported function.
    06CALLBACKPROC_API voidRegister_Callback(fnCallBackFunc func)
    07{
    08    intcount = 0;
    09  
    10    // let's send 10 messages to the subscriber
    11    while(count < 10)
    12    {
    13        // format the message
    14        std::stringstream msg;
    15        msg <<"Message #" << count;
    16  
    17        // call the callback function
    18        func(msg.str());
    19  
    20        count++;
    21  
    22        // Sleep for 2 seconds
    23        Sleep(2000);
    24    }
    25}
  5. 打开项目属性界面
  6. 确认目录名 “..\callbackproc” ,位置:C/C++->General->Additional Include Directories.
  7. 确认目录名 “..\callbackproc\debug” ,位置:Linker->General->Additional Libraries Directories. 在这个教程中我们使用 Debug 构建,你可根据需要自行修改
  8. 确认 “callbackproc.lib” 文件,位置:Linker->Input->Additional Dependencies
  9. 打开 CallbackSample.cpp 文件,并输入如下代码:
    01#include "stdafx.h"
    02#include <windows.h>
    03#include <string>
    04#include <windows.h>
    05#include <string>
    06  
    07#include "callbackproc.h"
    08  
    09// Callback function to print message receive from DLL
    10void CALLBACK MyCallbackFunc(std::string value)
    11{
    12    printf("callback: %s\n", value.c_str());
    13}
    14  
    15int _tmain(int argc, _TCHAR* argv[])
    16{
    17    // Register the callback to the DLL
    18    Register_Callback(MyCallbackFunc);
    19      
    20    return0;
    21}
  10. 当你尝试编译项目时需要注意 callbackproc 项目必须先编译,因为 CallbackSample 依赖于它
  11. 编译 CallbackSample 项目并运行,你会看到如下的输出信息
原创粉丝点击