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:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.