This article assumes that you have a working knowledge of C++ callbacks. Recently me and a friend encountered a situation where we had to show some data on dialog box that was generated inside of an independent thread. Sharing memory can be a good idea of passing a pointer to the dialog box. However, we could not pass the pointer as we had to keep the dependence to a minimum and he latter resulted in a cyclic reference, because we creating the thread from the dialog box class. What we wanted to do was to be able to make a call back to function as if it were not a member function (so as to reduce dependence). An obvious way to call a member function as a non member using a callback is to make that function static in the dialog class. However, it would create a slight problem, the static function would not be able to use any of the controls on the dialog box, beating us back to square one.
So I though of using the ‘this’ pointer. Obviously the ‘this’ pointer is not static and cannot be used in a static context. As a work around i introduced a static member inside the dialog box class that was a pointer to the dialog box class itself. Since this pointer was static it could be used from the static context of the function. Now to keep this pointer pointing to whatever ‘this’ is pointing to, one can either use the gain focus event of the dialog box or some other event as may be appropriate to make the static pointer equal to ‘this’ pointer. Once this is done the static function can use the static pointer to make changes inside the GUI, while the thread can call this function just like a normal function (non member).
Here is the signature i used to pass the function to the thread.
1:
2: void (*printFunction)(char * message);
This allows any function that accepts a char string and returns void to be used with the thread, allowing it to be used in many a context.
This article was written in very short time, if you find something lacking, please feel free to ask.
fit