Callbacks should always have context

Monday 30 December 2002

If you are designing an API, and you have callbacks in it, please: do us all a favor and let your caller provide a context for the callback. In other words, wherever the callback function is registered, take an another opaque data argument as well, and pass that data to the callback.

For example, in C, here's a function that could be used to register a malloc-like memory allocation callback:

void SetMallocCallback(
    void * (*pMalloc)(size_t size)

This works fine, as long as I want to implement a truly global malloc. Far better is this:

void SetMallocCallback(
    void * (*pMalloc)(void * pCtx, size_t size),
    void * pCtx

Now I can do more interesting things in my callback: I could create a local allocation pool, and pass it through the void * to a sub-allocating malloc, for example. Of course, if I want to write a simple global malloc, I still can, I just ignore the context data.

I apologize for the ugly C mess in these examples, but I hope you see what I'm getting at.


Add a comment:

Ignore this:
not displayed and no spam.
Leave this empty:
not searched.
Name and either email or www are required.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.