K
Kenneth Porter
I register with an external API to get callbacks upon physical events. The
events are queued and my generic callback is invoked from the API's thread.
I can pass a "context" to be included with the callback parameters.
I pass a pointer to my handler object and, when the generic callback is
invoked, I cast the pointer to the object and invoke it's handle() method.
The problem is that when I de-register interest in the events, the API is
documented to continue to call my callback until its queue is empty. That
means I don't know when it's safe to delete my handler objects. I need some
way to validate the context values passed to my generic handler before
using them as object pointers.
How do others handle this situation?
Some things I've considered:
Keep a magic number in my objects that I check for to see if the object
pointer is valid. Trash the magic number when the object is destroyed.
Keep a bag of valid object pointers and make sure the supplied context
pointer is in the bag before I use it.
If an object is deleted and another is created that happens to get the same
address, it might start getting events intended for the old object. I might
need to tag my objects with some kind of unique ID and use a hash of the
object as my event context, keeping a map between hashes and objects.
events are queued and my generic callback is invoked from the API's thread.
I can pass a "context" to be included with the callback parameters.
I pass a pointer to my handler object and, when the generic callback is
invoked, I cast the pointer to the object and invoke it's handle() method.
The problem is that when I de-register interest in the events, the API is
documented to continue to call my callback until its queue is empty. That
means I don't know when it's safe to delete my handler objects. I need some
way to validate the context values passed to my generic handler before
using them as object pointers.
How do others handle this situation?
Some things I've considered:
Keep a magic number in my objects that I check for to see if the object
pointer is valid. Trash the magic number when the object is destroyed.
Keep a bag of valid object pointers and make sure the supplied context
pointer is in the bag before I use it.
If an object is deleted and another is created that happens to get the same
address, it might start getting events intended for the old object. I might
need to tag my objects with some kind of unique ID and use a hash of the
object as my event context, keeping a map between hashes and objects.