[英]Cast std::bind function pointer to void* and back
假設我想綁定一個函數,然后將它作為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
則被稱為via
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::bind
的結果不是std::function
,如所示代碼所假設的那樣。
因此,當顯示的代碼將指針轉換為從std::bind
到void *
的返回值時,然后將其強制轉換為指向std::function
的指針,然后調用或訪問函數對象,這會導致未定義行為。
[func.bind.isbind]指定std::bind
,如下所示:
template <class F,class ... BoundArgs> unspecified bind(F && f,BoundArgs && ... bound_args);
返回值為:“具有弱結果類型的轉發調用包裝器g (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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.