boost::function对象 convert 函数指针
boost::function对象与函数指针比较相似,优点在于它拥有更大的弹性,目标既可以是普通函数、函数对象或者类的成员函数,而且还可绑定参数,给回调提供了极大的方便。但是C语言的函数是不支持boost::function对象的,当需要函数指针的C函数填写上boost::function对象时候,就出现下面的error [color=red]cannot convert 'boost::function[/color]'[color=red] to[/color] 'void* (*)(void*)' 其实我们可以在中间加上一个proxy的函数来解决 如下,pthread_create需要的为函数指针,而我们需要绑定一些参数,我们就可以创建一个proxy代理函数,代理函数复合pthread_create所需函数的要求,但在代理函数里边执行我们的boost::function对象表示的函数。 [code="java"]#include #include #include #include #include #include #include #define LOG(content) cout<* threadFunction = reinterpret_cast *>(agrv); (*threadFunction)(NULL); return NULL; } int main() { int a = 10, b = 20; pthread_t threadId; boost::function< void*(void *)> threadFunction = boost::bind( realThreadFunction, a, b, _1); if (0 == pthread_create(&threadId, NULL, proxyThreadFunction, &threadFunction)) { boost::this_thread::sleep(boost::posix_time:: seconds(5)); pthread_join(threadId, NULL); } else { LOG( "create thread fail.") } return 0; } [/code]