patternscallback-context
Callback + Context Pattern (C-Specific) pattern for C development
When & Why to Use This Skill
This Claude skill facilitates the implementation of the Callback + Context pattern in C development, a fundamental design pattern for managing state in asynchronous systems. By pairing function pointers with 'void *' user data, it enables developers to create modular, thread-safe, and maintainable code that avoids the pitfalls of global variables.
Use Cases
- Streaming API Responses: Handling incremental data chunks (like LLM outputs) while maintaining local state within a specific request context.
- Event-Driven Programming: Implementing GUI or network event listeners where the callback needs access to specific object instances or data structures.
- Library Development: Designing generic C libraries that allow users to pass custom context into internal processing loops or interrupt handlers.
- Multi-threaded Task Execution: Passing unique state information to worker threads without risking data races associated with shared global memory.
| name | patterns/callback-context |
|---|---|
| description | Callback + Context Pattern (C-Specific) pattern for C development |
Callback + Context Pattern (C-Specific)
Pair function pointer with void * user data. Callback receives user data, enabling state access without globals. Universal C pattern for async/event handling.
ikigai Application
Streaming responses:
typedef void (*chunk_cb_t)(void *user_ctx, const char *data, size_t len);
res_t ik_llm_stream(ik_llm_client_t *client,
ik_message_t **msgs,
chunk_cb_t on_chunk,
void *user_ctx); // Passed to callback
Usage: REPL passes itself as context, callback updates scrollback.
Convention: Callback function pointer immediately followed by void * context parameter. Callback signature includes context as first param.
Benefit: Stateful callbacks without globals. Each caller provides own context.