Search code examples
c++type-conversionvoid-pointersdynamic-librarydlsym

What is the C++ way of interpreting the void* returned by dlsym as a pointer-to-function?


Assume a dynamic library exports a function, e.g. of type void(), named foo. A client code could then make use of it like in the following snippet (assuming foo is exposed via extern "C" void foo(); for simplicity)

#include "Foo.hpp" // defines the type of foo

// dlopen a library and check it was found

// look for a symbol foo in a library lib
void * fooPtr = dlsym(lib, "foo");

// if reading the symbol succeeded
if (!dlerror()) {
  // use it
  using Foo = decltype(foo);
  ((Foo*)fooPtr)();
}

I've understood that static_cast is not usable here, but is the above C-style cast the way to go?


Solution

  • The C-style cast is required in archaic versions of C++. Since C++11, reinterpret_cast from object pointer to function pointer type is conditionally-supported and should be used if possible:

    #if __cplusplus >= 201103L
      reinterpret_cast<Foo*>(fooPtr)();
    #else
      ((Foo*)fooPtr)();
    #endif
    

    If the implementation supports dlsym (which is part of POSIX), it almost certainly supports reinterpret_cast from object pointer to function pointer type.