Originally Posted by
C+/-
I'm not sure. I don't understand what you mean by "opaque pointer". What is an opaque pointer in this context?
Also, in order for the library to pass an object to the callback, it has to store it. But it can't know its type (or at least I don't want it to).
Right -- that's what an opaque pointer is.
Okay, there are three ways to deal with this, not two. The way you just suggested is the third -- instead of passing a pointer to a function, pass a pointer to an object, which implements some base interface. I.e.:
Code:
class event_base
{
virtual ~event_base() {}
virtual void do_event(unsigned char* data, unsigned int dataLength, SystemID sourceSystem) = 0;
};
class my_event_handler : public event_base
{
virtual void do_event(unsigned char* data, unsigned int dataLength, SystemID sourceSystem)
{
// Do your stuff
}
};
Then you create a my_event_handler, and pass it to the setEventFunction() method. This method will take an event_base pointer, not a my_event_handler pointer, and the call is virtual. Does that make sense?
The templatized version is actually pretty complicated, and I'm thinking it's probably not the best solution in this case.
The opaque pointer method would be as follows:
Code:
void setEventFunction(MessageID messageID, PacketHandler packetHandler, void *handlerData);
With the PacketHandler modified to be:
Code:
typedef int (*PacketHandler)(unsigned char* data, unsigned int dataLength, SystemID sourceSystem, void *handlerData);
So when you set the handler, you pass a pointer to the MyClass object as "handlerData" -- the handler function itself will receive this pointer as its last argument, cast it back to MyClass, and invoke whatever it needs to.
But that's a very C-ish way of doing it. Your suggestion is actually best I think.