Rapscallion said:
This is a typical C solution. In C++ you have more and better (i.e.
typesave) options.
The original question was about the callback function, whether it should be
a static member function or a global function, and he was wondering about
how to access non-static members from that function. I told him how I've
generally implemented them and used them to accomplish the task.
This method calls a C++ member function, so it's hardly typical C. And I
can pass the void* pointer as a base class pointer if needed, so that
run-time polymorphism can be used.
It does require that there be a field useable to specify the object instance
when "registering" for the callbacks. This field is usually specified as a
void* pointer, to allow you to pass any kind of object at all for any
purpose you desire. I pass the instance of my object. Since the entire
callback is simply a one-liner that casts my pointer to my _known_ object
type and calls its member function, I don't really have to worry about type
safety. (Assuming I don't get someone else's callbacks...in which case
either the callback mechanism is broken or I didn't RTFM.)
Although you didn't specify an alternate method, I suppose you could use
templates. I haven't thought it out, but it sounds like the best
"all-purpose" solution to me, if you're sticking to C++ callback clients
only.
But I suspect that most API's I've worked with don't really care if you're
calling their library from C or C++ (or even something else), so they just
go with a generic void* pointer. And, I don't recall any API I've used
implementing their callbacks as templates...so far they've all provided a
void* pointer for my use.
-Howard