---
title: "boost::function对象  convert  函数指针"
author: "OrangeHolic"
date: "2014-10-31T15:29:44Z"
tags: ["C"]
categories: ["互联网"]
slug: "boost-function-convert"
draft: false
lastmod: "2014-10-31T15:29:32Z"
id: 2150161
url: "https://orangeholic.iteye.com/blog/2150161"
---

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&lt;* threadFunction = reinterpret\_cast \*&gt;(agrv); (\*threadFunction)(NULL); return NULL; } int main() { int a = 10, b = 20; pthread\_t threadId; boost::function&lt; void\*(void \*)&gt; 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]