假设我想绑定一个函数,然后将其作为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));
同时,myfunc
是MyObj<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.
我相信我有我的演员的打字错误,但我不知道正确的方式来声明类型。什么是正确的方法来做到这一点?
公平点,更新。 –
感谢您的回复,但这里的解决方案究竟是什么?我的返回类型应该是什么? std :: function是一个模板类型,并使用我选择的模板不能编译:“错误C2893:未能专用函数模板'未知类型std :: invoke(_Callable &&,_类型&& ...)'“ – user650261
正如我写的,解决方案是显式地将'std :: bind'的返回值赋给相应的'std :: function',而不是'auto'。 –