I am trying to interface with a library written in c
, that uses this familiar pattern:
void some_c_handler(void(*func)(void*), void* data);
Now, I want to write a C++
wrapper for this function that looks like this:
void my_new_cpp_handler(std::function<void()>&& func)
{
void (*p)() = foo(func);
void* data = bar(func);
some_c_handler(p, data);
}
Both some_c_handler
and my_new_cpp_handler
are solving the same problem; they're taking in some kind of function along with some state. But the latter is preferred in that it abstracts much of the implementation details from the user, and allows for simply passing in a lambda object.
So my_new_cpp_handler
should take the func
parameter it is given, convert it to a function pointer and pass its state on to data
.
I don't know enough about the standard, or the implementation of std::function
to know if this is even a reasonable request. Can foo
and bar
exist?
To put it differently, what I want is to be able to pass a stateful function to a c
callback handler without having to manually instantiate my own struct
type to pass along with it. Obviously std::function
has already done this for us, so I'd love to be able to separate the function pointer from the state somehow and pass it onto the c
-style handler. Is this possible?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…