boost::function对象 convert 函数指针

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

[color=red]cannot convert 'boost::function[/color]<void*(void*)>'[color=red] to[/color] '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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值