Imaging that your application need to load a DLL, which it could be your self-developed DLL or 3rd party DLL, and your application is dependent on some input or data from the DLL. Most DLL will provides APIs for calling the right function in order to execute certain processes to get the return value from the API.

Calling the DLL’s API periodically is expensive. You will need to add extra efforts to run the scheduler. Moreover, it doesn’t guarantee that the API will return the right value due to the unavailability of return data.

To reduce the overhead, we could create a callback function and register it to the DLL. In this case, we don’t have to create a scheduler to call the DLL’s API periodically. In fact, the DLL will call the callback function and trigger our application whenever the data is available.

This tutorial will guide you on how to create a callback function and register it to a DLL. Visual C++ Callback Function Example

The Solution
  1. Create a Win32 Console application project. Name the project “SampleCallback”. Make sure that the application type is console application.
  2. Add a new Win32 Console application project to the same solution. Name the project “callbackproc”. Make sure that the application type is DLL. Visual C++ Callback Function Example
  3. callbackproc project
  4. Open the callbackproc.h file and enter the following.

  5. Open the callbackproc.cpp file and enter the following.
  6. CallbackSample project
  7. Open the project properties page.
  8. Make sure that the directory name “..\callbackproc” is in the C/C++->General->Additional Include Directories.
  9. Make sure that the directory name “..\callbackproc\debug” is in the Linker->General->Additional Libraries Directories. I make debug build in this tutorial. You might need to change according to your selection. :)
  10. Make sure that “callbackproc.lib” file is in the Linker->Input->Additional Dependencies
  11. Open the CallbackSample.cpp file and enter the following.
  12. Output
  13. Be careful when your try to compile the projects. Make sure that callbackproc project is always get compile first. This is because CallbackSample project is dependent on it.
  14. Compile CallbackSample project now and run it. You should observe the following output where the DLL will call the callback function for 10 times before it end the operation.
    Visual C++ Callback Function Example

Download source code: CallbackSample.zip