I have a (modifiable) C API that calls my C++ code back from a POSIX thread. Because directly calling non-static member functions from plain C is impossible, I have set up a static wrapper which uses a pointer provided by the callback caller to refer to the instance of the class as described in two other questions and very verbosely here.
The major pita (as a Java-spoiled C++ newbie :) is that this
does not seem to be very stable at all. For example, if I store the objects I just registered to the callback in a Vector with push_back
it seems as if the old object's life is over after going out of scope and only a copy is stored in the Vector. This produces fancy explosions but that's not what I am looking for ;)
What options do I have to mitigate this problem?
Since it was requested let me show the current state/problem:
std::vector<A> v;
{
A cur(...);
cur.set_handler(); /* to avoid leaking 'this' in the constructor */
v.push_back(cur); /* creates a copy of cur */
} /* I presume cur is destroyed here */
Important parts of class A:
handler_t handler;
void A::set_handler() {
handler.handle = handle_stuff_static;
handler.user_data = this;
add_handler(&handler); /* C function which stores the pointer for further reference (no pun intended) */
}
void A::handle_stuff_static(void *user_data) {
if (user_data != NULL)
static_cast<A *>(user_data)->handle_stuff_instance();
}
void A::handle_stuff_instance() { /* non-static member function */
// hurray
}