the function pointer void*
is loaded by dlsym()
, can I cast it to std::function
?
suppose the function declaration in lib is
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?
No, the function type int(int)
and the class type std::function<int(int)>
are two different types. Whenever you use dlsym
, you must cast the resulting pointer only to a pointer to the actual type of the symbol. But after that, you can do with it what you want.
In particular, you can construct or assign a std::function
from a pointer to function:
using RawFuncType = int(int);
std::function<int(int)> f{
reinterpret_cast<RawFuncType*>(dlsym(libHandle, "func")) };
Write something like this:
template<class T>
T* dlsym_ptr(void* handle, char const* name) {
return static_cast<T*>( dlsym( handle, name ) );
}
then:
FuncType f = dlsym_ptr<int(int)>(libHandle, "func");
works, and it isolates the cast into a helper function.
Note that when casting from void*
to another pointer type, use static_cast
. Only use reinterpret_cast
when nothing else works, and static_cast
explicitly lets you convert from void*
to any other pointer type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With