考虑以下类
class Foo
{
public:
void* func(void* arg)
{
// how to pass this function to pthread...?!
}
}
Run Code Online (Sandbox Code Playgroud)
后来我想传递func()给pthread_create(), 而不是一个函数:
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 );
}
Run Code Online (Sandbox Code Playgroud)
提前致谢。
“通常”的方法是,将对象和所有函数参数打包到一个结构中,在堆上分配此结构,将此结构的实例传递给具有 C 绑定的函数,并让该函数调用对象成员函数:
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 );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11893 次 |
| 最近记录: |