c++ - How to use lambda functions or std::function with an API that takes function pointers? -
suppose want implement simple abstraction on pthreads. (or c api takes function pointers callbacks or threads).
like std::thread, want interface able take function objects in general.
how bridge gap in way works cases? (that includes binds, lambda functions, etc.)
i know std::function::target afaik, not need.
if api takes functions void*
user data as, e.g., pthread_create()
does, you'd pass pointer function user data, call trampoline casts user data function type, , calls function. example:
#include <functional> #include <pthread.h> extern "c" void* trampoline(void* userdata) { return (*static_cast<std::function<void*()>*>(userdata))(); } void* start() { // ... return 0; } int main() { pthread_t thread; std::function<void*()> entry(start); pthread_create(&thread, 0, &trampoline, &entry); // ... }
the immediate implication is, however, function object life-time isn't controlled. in example above std::function<void*()>
object happens live long enough isn't easy.
if function try call doesn't have user data argument, pretty out of luck. might away using global objects rather fragile approach.
Comments
Post a Comment