Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

c++ - Cast member function for create_pthread() call

I want to stop the warning

server.cpp:823: warning: converting from 'void* (ClientHandler::)()' to 'void ()(void)'

in the call:

pthread_create(th, NULL,
    (void* (*)(void*)) &ClientHandler::handle,
    (void *) clientHandler);

where handle() is a member function of ClientHandler:

void* ClientHandler::handle();

I have difficulties deciphering the function-type message from the compiler.

The question is:

  • Should I change the handle() interface? Can I get rid of casting overall?
  • Should I change the cast? To what exactly?
  • Something completely different?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't do that directly, pointers to member functions are not plain pointers to functions and can't be handed over to C callbacks directly.

You'll need one level of indirection:

void callHandle(void *data) {
  ClientHandle *h = static_cast<ClientHandle*>(data);
  h->handle();
}

pthread_create(th, 0, &callHandle, static_cast<void*>(handle));

See the Pointers to members section of the C++FAQ for more information / alternatives.

For the validity of the cast in callHandle, see this question. You are sole responsible for making sure that handle is still alive and well when callHandle is called of course (and for the fact that it actually points to a ClientHandle).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...