How do you pass C++ state to a C-style callback that takes a function pointer and a void* user argument?
answer
- function pointers carry no state
- the void* is the state channel
- cast back to the exact type
- captureless lambdas convert
basics
~20 sPass a free function or captureless lambda as the function pointer and the address of your state as the void* argument; inside the callback, static_cast the void* back to exactly the pointer type you passed in.
solid answer
~40 sA function pointer such as `using PixelFn = void (*)(void*, unsigned char*);` names code only, so state has to travel separately: the C API's `void* user` parameter. Pass `&state`, and in the callback write `static_cast<Threshold*>(user)` - the round trip `T*` to `void*` to `T*` gives back the original pointer. Casting to a *different* type, such as a base class of what you stored, compiles but is not guaranteed to give a pointer to an object of that type - with multiple inheritance it visibly does not - so using it is undefined. A captureless lambda converts implicitly to the function pointer type; a capturing lambda has no such conversion and is rejected. `std::function` cannot be passed either. The state object must outlive every call the library may make.
code
cpp · 27 lines#include <cstdio>
#include <type_traits>
// A C-style filter API: one callback per pixel plus an opaque user pointer.
typedef void (*PixelFnC)(void* user, unsigned char* px); // C spelling
using PixelFn = void (*)(void* user, unsigned char* px); // C++11 alias, same type
static_assert(std::is_same_v<PixelFnC, PixelFn>);
void for_each_pixel(unsigned char* buf, int n, PixelFn fn, void* user) {
for (unsigned char* p = buf; p != buf + n; ++p) fn(user, p);
}
struct Threshold { unsigned char cut; int hits = 0; };
void apply_threshold(void* user, unsigned char* px) {
auto* t = static_cast<Threshold*>(user); // back to the exact type that went in
if (*px >= t->cut) { *px = 255; ++t->hits; } else { *px = 0; }
}
int main() {
unsigned char row[5] = {12, 200, 90, 130, 255};
Threshold t{128};
for_each_pixel(row, 5, apply_threshold, &t);
// A captureless lambda converts implicitly to the function pointer type.
for_each_pixel(row, 5, [](void*, unsigned char* px) { *px /= 2; }, nullptr);
std::printf("hits=%d first=%d last=%d\n", t.hits, row[0], row[4]);
}go deeper
Recall the function pointer declaration syntax, that a using alias makes it readable, and that a captureless lambda converts to a function pointer.
Explain the code-plus-void* split, the static_cast back to the exact type, and why capturing lambdas and std::function cannot be passed.
Name the multiple-inheritance trap of casting void* to a base, catch exceptions inside callbacks, and check that the state outlives every registered callback.
Define one trampoline pattern for wrapping C callback APIs, with lifetime ownership and exception boundaries agreed once for the codebase.
## Function pointer syntax A **function pointer** holds the address of a function with one exact signature. The declarator reads inside out, which is why aliases are the norm: ```cpp void (*fn)(void*, unsigned char*); // a variable typedef void (*PixelFnC)(void* user, unsigned char* px); // C spelling using PixelFn = void (*)(void* user, unsigned char* px); // C++11 alias ``` `PixelFnC` and `PixelFn` are the same type. A function name converts to a pointer to it implicitly (`fn = apply_threshold;`), and calling through the pointer needs no `*` (`fn(user, p);`). A function returning a function pointer is where aliases stop being optional: `PixelFn pick(int mode);` instead of `void (*pick(int mode))(void*, unsigned char*);`. ## The state problem A C library such as an image-processing callback table cannot accept C++ closures. Its interface is a pair: 1. a function pointer - **code only**, no captured data; 2. a `void* user` argument that the library stores and hands back untouched on every call. The `void*` is your state channel. You pass the address of a C++ object; the callback converts it back. The standard specifies the round trip: converting a `T*` to `void*` and `static_cast`-ing it back to `T*` yields the original pointer value. `static_cast` is the right cast for `void*` to object pointer; `reinterpret_cast` also works but says less. ## Converting back to the wrong type The conversion from `void*` checks nothing. If the library is handed a `Blur*` stored as `void*`, and the callback does `static_cast<Filter*>(user)` where `Filter` is the **second** base of `Blur`, the result is the unchanged `Blur` address, which does not point to a `Filter` subobject - using it is undefined behaviour. With a single, non-virtual base it usually happens to work, which is why the bug survives until someone adds a base class. The rules: - cast back to **exactly** the type you converted from; - if the callback needs a base, cast to the derived type first and let the implicit derived-to-base conversion adjust the address; - or always store a pointer of the agreed interface type (`Filter*`) and convert that to `void*`. ## Lambdas and other callables | Callable | Converts to `PixelFn`? | State | |---|---|---| | free function / static member function | yes | via `void*` | | captureless lambda | yes, implicitly | via `void*` | | lambda with captures | no - "no known conversion" | captured, but unusable here | | `std::function<void(void*, unsigned char*)>` | no | owned by the wrapper | | member function pointer | no - different kind of type | needs an object | A **captureless lambda** has a conversion function to a pointer to function with the same parameters, so it can be passed inline. A common trick is a captureless trampoline lambda that casts `user` back to the real object and calls a member function on it. Capturing lambdas, `std::function` and member function pointers belong to the material on invocable wrappers and lambdas; the point here is that none of them is a plain function pointer. ## Edge rules worth knowing - Converting a function pointer to `void*` (or back) is **conditionally-supported** with implementation-defined meaning; POSIX `dlsym` relies on platforms supporting it, but the C++ standard does not guarantee it. Never store a function pointer in the `void* user` slot of portable code. - **Language linkage** is part of a function type in the standard: a function type with C linkage and one with C++ linkage are distinct. For a library that declares its callback type inside `extern "C"`, the portable callback is a free function also declared `extern "C"`. - Do not let an exception propagate out of a callback through the C library's frames: C code is not written to be unwound through, and whether unwinding even works depends on the platform and how the library was built. Catch everything inside the callback. - **Lifetime**: the object behind `user` must outlive the last callback; registering `&local` with a library that calls back later is a dangling-pointer bug. ## Summary for the interview State the split - function pointer for code, `void*` for data - show the `static_cast` back to the exact type, mention that captureless lambdas convert and capturing ones do not, and close with the multiple-inheritance trap and the lifetime of the state object.
- How do you route a C callback to a member function of a C++ object?Register a captureless lambda or a static member function as the trampoline and the object's address as `user`. The trampoline does `static_cast<Engine*>(user)->on_pixel(px);`. The member function itself cannot be passed, because a pointer to member function needs an object to call it and is not convertible to an ordinary function pointer.
- Can you store a function pointer in the void* user argument instead of an object pointer?Not portably. Converting a function pointer to an object pointer type such as `void*` and back is conditionally-supported in C++, with implementation-defined meaning. POSIX platforms support it because `dlsym` depends on it, but portable code wraps the function pointer in a struct and passes the struct's address instead.
- A capturing lambda converts to a function pointer if the signature matches
- Casting the void* to a base class of the stored object is always safe
- std::function can be passed wherever a C function pointer is expected
- Any pointer, including a function pointer, converts to void* and back portably
- The user object can be a local variable even if callbacks arrive later