Using a callback function is the common way.
Searching the net for "c++ callback dll example" gives you enough results.
askyb.com » Visual C++ Callback Function Example[
^] is a short and simple explanation.
But there is one point to observe when using callback functions with DLLs (which is not mentioned in the above link):
A DLL may be used by multiple applications at the same time including multiple instances of the same (your) program. The DLL must be able to handle this by providing a register function to add a new callback function, an unregister function to remove it, and loop through all registered ones and call them upon the event.
So you need to
- Understand C/C++ callback functions
- Define the callback function (return value and parameter types) using a
typedef
- In the DLL add a list variable to hold the callback function pointers
- In the DLL implement the register and unregister functions
- In the DLL call the registered functions upon the event
- In the app implement the static callback function
- In the app call the register and unregister functions (e.g. at program start and exit)
Because callback functions are static, they can be class members but have no access to other (non-static) class members. But you usually want to pass the event from the callback function to a class of your application. A solution to this problem is passing a pointer to this class (or even a void pointer which is more flexible) as parameter. This requires that this pointer is also passed to the register function and stored in the list.
Short example for the public functions of the DLL in the header file:
# ifdef CALLBACKPROC_EXPORTS
# define CALLBACKPROC_API __declspec(dllexport)
# else
# define CALLBACKPROC_API __declspec(dllimport)
# endif
typedef void (CALLBACK * callBackFnType)(void *p, int event);
extern "C"
{
CALLBACKPROC_API void RegisterCallback(callBackFnType func, void *p);
CALLBACKPROC_API void UnregisterCallback(callBackFnType func);
}
typedef struct {
callBackFnType func;
void *p;
} CallBackItem;