【发布时间】:2012-10-25 15:21:03
【问题描述】:
我有一个第三方库,它有一个将函数指针作为第一个参数的方法:
int third_party_method(void (*func)(double*, double*, int, int, double*), ...);
我想传递一个指向类方法的指针,声明如下:
class TestClass
{
public:
void myFunction (double*, double*, int, int, void*);
我尝试如下传递这个函数:
TestClass* tc = new TestClass();
using namespace std::placeholders;
third_party_method(std::bind(&TestClass::myFunction, tc, _1, _2, _3, _4, _5), ...);
但是,这不会编译:
Conversion of parameter 1 from 'std::tr1::_Bind<_Result_type,_Ret,_BindN>' to 'void (__cdecl *)(double *,double *,int,int,void *)' is not possible
with
[
_Result_type=void,
_Ret=void,
_BindN=std::tr1::_Bind6<std::tr1::_Callable_pmf<void (__thiscall TestClass::* const )(double *,double *,int,int,void *),TestClass,false>,TestClass *,std::tr1::_Ph<1>,std::tr1::_Ph<2>,std::tr1::_Ph<3>,std::tr1::_Ph<4>,std::tr1::_Ph<5>>
]
有什么方法可以将成员传递给函数吗?
【问题讨论】:
-
没有。您需要编写一个具有所需签名的函数。你不能从函数对象中获得一个指针。
-
不可能 - 见question。
-
如果您的第三方库要求您提供回调而没有提供某种不透明上下文参数的功能,那么您基本上注定要失败。如果对该库的访问是单线程的,或者由持有回调函数的对象实例进行多线程的访问在运行时从不改变,则可以使用普通函数和指向类实例的静态指针。责备第三方;如果你已经付钱给他们,你可能会为此而麻烦他们。
-
对于其他从 C 转向 C++ 的人:不要将回调定义为函数指针,而是使用 functors。查找
std::function。然后您就可以将this指针绑定到一个方法,并将其作为“函数指针”(函子)传递。
标签: c++ function-pointers