Passing Derived Class Instances as void* to Generic Callbacks in C++
- by Matthew Iselin
This is a bit of an involved problem, so I'll do the best I can to explain what's going on. If I miss something, please tell me so I can clarify.
We have a callback system where on one side a module or application provides a "Service" and clients can perform actions with this Service (A very rudimentary IPC, basically). For future reference let's say we have some definitions like so:
typedef int (*callback)(void*); // This is NOT in our code, but makes explaining easier.
installCallback(string serviceName, callback cb); // Really handled by a proper management system
sendMessage(string serviceName, void* arg); // arg = value to pass to callback
This works fine for basic types such as structs or builtins.
We have an MI structure a bit like this:
Device <- Disk <- MyDiskProvider
class Disk : public virtual Device
class MyDiskProvider : public Disk
The provider may be anything from a hardware driver to a bit of glue that handles disk images. The point is that classes inherit Disk.
We have a "service" which is to be notified of all new Disks in the system, and this is where things unravel:
void diskHandler(void *p)
{
Disk *pDisk = reinterpret_cast<Disk*>(p); // Uh oh!
// Remainder is not important
}
SomeDiskProvider::initialise()
{
// Probe hardware, whatever...
// Tell the disk system we're here!
sendMessage("disk-handler", reinterpret_cast<void*>(this)); // Uh oh!
}
The problem is, SomeDiskProvider inherits Disk, but the callback handler can't receive that type (as the callback function pointer must be generic).
Could RTTI and templates help here?
Any suggestions would be greatly appreciated.