boost::function对象 convert 函数指针

boost::function对象与函数指针比较相似,优点在于它拥有更大的弹性,目标既可以是普通函数、函数对象或者类的成员函数,而且还可绑定参数,给回调提供了极大的方便。但是C语言的函数是不支持boost::function对象的,当需要函数指针的C函数填写上boost::function对象时候,就出现下面的error

cannot convert 'boost::function<void*(void*)>' to 'void* (*)(void*)'

其实我们可以在中间加上一个proxy的函数来解决

如下,pthread_create需要的为函数指针,而我们需要绑定一些参数,我们就可以创建一个proxy代理函数,代理函数复合pthread_create所需函数的要求,但在代理函数里边执行我们的boost::function对象表示的函数。

#include <iostream>
#include <string>
#include <thread>
#include <boost/format.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

#define  LOG(content) cout<<content<<endl;

using namespace std;

void* realThreadFunction( int first, int second, void *agrv) {

     //Do things with first and second

     string content = (boost:: format( "%1% + %2% = %3%") % first % second
              % (first + second)).str();

     LOG(content);
     return NULL;

}

void* proxyThreadFunction( void * agrv) {

     boost::function< void*(void *)>* threadFunction =
               reinterpret_cast<boost::function <void*(void *)> *>(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;
}
 

猜你喜欢

转载自orangeholic.iteye.com/blog/2150161