[英]Can I cast function pointer void* to std::function?
函數指針void*
由dlsym()
加載,我可以將其std::function
為std::function
嗎?
假設lib中的函數聲明是int func(int);
using FuncType = std::function<int(int)>;
FuncType f = dlsym(libHandle, "func"); // can this work?
FuncType f = reinterpret_cast<FuncType>(dlsym(libHandle, "func")); // how about this?
不,函數類型int(int)
和類類型std::function<int(int)>
是兩種不同的類型。 每當使用dlsym
,必須將結果指針僅轉換為指向符號實際類型的指針。 但在那之后,你可以用它做你想要的。
特別是,您可以從指向函數的指針構造或分配std::function
function:
using RawFuncType = int(int);
std::function<int(int)> f{
reinterpret_cast<RawFuncType*>(dlsym(libHandle, "func")) };
寫下這樣的東西:
template<class T>
T* dlsym_ptr(void* handle, char const* name) {
return static_cast<T*>( dlsym( handle, name ) );
}
然后:
FuncType f = dlsym_ptr<int(int)>(libHandle, "func");
工作,它將演員陣容隔離成輔助函數。
請注意,從void*
為另一種指針類型時,請使用static_cast
。 只有在沒有其他工作時才使用reinterpret_cast
, static_cast
顯式允許您從void*
轉換為任何其他指針類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.