2016-12-04 327 views
1

假设我想绑定一个函数,然后将其作为void *传递给另一个函数,并将其转回。将std :: bind函数指针转换为void *并返回

我有一个全局函数中,我试着投功能:

void function_wrapper(void * func){ 

std::function<void(const std::vector<double>&, const std::vector<double>&)> * function = reinterpret_cast<std::function<void(const std::vector<double>&, const std::vector<double>&)> *>(func); 

std::function<void(const std::vector<double>&, const std::vector<double>&)> function_ = *function; 
} 

FUNC,同时,将创建为:

auto func = std::bind(&MyObj<dim>::myfunc, this, _1, _2); 

这里dim等于2和模板化的整数function_wrapper通过

function_wrapper((void *)(&func)); 

同时,myfuncMyObj<dim>与类型的方法:

void myfunc(const std::vector<double>& x, std::vector<double>& F) const; 

当我尝试调用function_wrapper如上所述,我得到以下错误,当我解除引用它:

Exception thrown: read access violation. 

std::_Func_class<void,std::vector<double,std::allocator<double> > const & __ptr64,std::vector<double,std::allocator<double> > const & __ptr64>::_Getimpl(...) returned 0xFFFFFFFFFFFFFFFF. 

If there is a handler for this exception, the program may be safely continued. 

我相信我有我的演员的打字错误,但我不知道正确的方式来声明类型。什么是正确的方法来做到这一点?

回答

0

std::bind的结果不是std::function,如显示的代码所假定的。

这样,当所示出的代码铸指针从std::bindvoid *返回值,然后投射回一个指向std::function,然后调用或访问功能对象,这导致未定义的行为。

[func.bind.isbind]指定std::bind如下:

模板< F级,类... BoundArgs > 未指定绑定(F & &楼 BoundArgs & & ... bound_args);

随着返回值:“一个转发调用包装有弱的结果类型(20.9.2)G的影响(U1,U2,...,UM)应的invoke( fd,std :: forward(v1),std :: forward(v2),...,std :: forward(vN),result_of_t)“。

就是这样。由std::bind返回的类是未指定的,虽然它肯定允许给定的C++实现以某种方式产生std::function,但不要求这样做。

但是,解决方案很简单:将返回值从std::bind明确分配给合适的std::function

+0

公平点,更新。 –

+0

感谢您的回复,但这里的解决方案究竟是什么?我的返回类型应该是什么? std :: function是一个模板类型,并使用我选择的模板不能编译:“错误C2893:未能专用函数模板'未知类型std :: invoke(_Callable &&,_类型&& ...)'“ – user650261

+0

正如我写的,解决方案是显式地将'std :: bind'的返回值赋给相应的'std :: function',而不是'auto'。 –

相关问题