pass the class method as pthread start function
c++, multithreading, pointers
Solution
The 'usual' approach is, to pack the object and all function arguments into a struct, allocate this struct on the heap, pass an instance of this struct to a function with C binding and let that function call the objects member function:
struct wrap {
char * msg;
Foo ins;
wrap( char* m, const Foo& f ) : msg(m), ins(f) {}
};
extern "C" void* call_func( void *f )
{
std::auto_ptr< wrap > w( static_cast< wrap* >( f ) );
w->ins.func(w->msg);
return 0;
}
int main() {
wrap* w = new wrap( "Hi dude", Foo() );
pthread_t pt;
pthread_create( &pt, NULL, call_func, w );
}
Problem
Considering the following class ``` class Foo { public: void* func(void* arg) { // how to pass this function to pthread...?! } } ``` Later I want to pass `func()` to `pthread_create()`, instead of a function: ``` int main() { char * msg = "Hi dude"; Foo * ins = new Foo(); pthread_t pt; // how to pass ins->func instead of a function? pthread_create( &pt, NULL, ins->func, (void*)msg ); } ``` Thanks in advance.