Sign in to follow this  
Concentrate

Need help to solve this passing member function pointer

Recommended Posts

I can't use boost. So with that in mind. I have a class called Thread like so :
[code]
class Thread{
public:
typedef void*(*StartRoutine)(void*);
private:
pthread_t _thread;
public:
Thread(){}
void start(const StartRoutine initFunc, void* arg){
pthread_create(&_thread,NULL,initFunc,arg);
}
void waitToEnd(){
pthread_join(_thread,NULL);
}

};
[/code]

and I want to call the start() function like so :
[code]
void startRequesting(){
_thread.start(&(this->_run), NULL );
}
private:
void* _run(void* arg){
while(!_jobs.empty()){
_scheduler->addJob( _jobs.front()); //ask for job request
_jobs.erase(_jobs.begin()); //remove that job after put into the buffer
}
return arg;
}
[/code]

but that doesn't work. What option do I have?

Share this post


Link to post
Share on other sites
You need a trampoline function. A namespace-level or static member function that calls your regular member function.
[code]
static void trampoline(void* arg)
{
Runner* runner = static_cast<Runner*>(arg);
runner->run();
}

// here's your code, modified
void startRequesting()
{
_thread.start(trampoline, this);
}
[/code]

Share this post


Link to post
Share on other sites
[quote name='D.Chhetri' timestamp='1302386564' post='4796502']
wow sweet. Nice wrapper idea. Is it really called a trampoline function?
[/quote]

"Wrapper", "adapter", and other names exist.

Share this post


Link to post
Share on other sites
Just a side note:
Don't use variable names like _foobar or foobar_.
Names with _ on front of the var or at the end are reserved to the compiler.
And yes, this solution is perfectly portable.
You can use this approach whenever a userpointer can be passed to a C-Callback. This way you can also wrap WinProc etc in Windows.
Another solution can be to use boost::bind to bind a member-function directly, or std::tr1::bind which is the same but needs support for C++0x TR1 in your compiler.

Share this post


Link to post
Share on other sites
[quote]
Names with _ on front of the var or at the end are reserved to the compiler. [/quote]
Incorrect.

Trailing underscores are never reserved.

Beginning underscores are more complex. Anything beginning with two underscores or an underscore and an uppercare letter is reserved. Globally scoped names beginning with an underscore are reserved for the compiler.

But I agree in principle, the decoration is unnecessary.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this