Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cast function pointer void* to std::function?

Tags:

c++

c++11

c++14

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?
like image 420
mewo1234 Avatar asked Jan 30 '18 03:01

mewo1234


2 Answers

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")) };
like image 64
aschepler Avatar answered Sep 19 '22 16:09

aschepler


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.

like image 36
Yakk - Adam Nevraumont Avatar answered Sep 17 '22 16:09

Yakk - Adam Nevraumont