1

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?

Enlico
  • 23,259
  • 6
  • 48
  • 102
  • 1
    https://stackoverflow.com/questions/55362913/how-to-load-function-with-dlsym-without-reinterpret-cast – ecatmur Oct 09 '22 at 07:43
  • @ecatmur, yeah, probably that's an answer to my question. I'll let others mark this as dup. – Enlico Oct 09 '22 at 07:51
  • Does this answer your question? [How to load function with dlsym() without reinterpret\_cast?](https://stackoverflow.com/questions/55362913/how-to-load-function-with-dlsym-without-reinterpret-cast) – Homer512 Oct 09 '22 at 08:18
  • There are different methods, but the result is the same (i.e. the actual 32/64 bits of the pointer aren't changed), so no need to put too much effort into it. – Lorinczy Zsigmond Oct 09 '22 at 17:43

1 Answers1

1

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.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • `reinterpret_cast` is clearer, but it has the same effect as the C-style cast. So if the latter needs to be supported it seems pointless to conditionally use `reinterpret_cast`. Actually, did you maybe intent to reinterpret the pointer itself in the else-branch? That is the aliasing-violating approach I am have seen when the cast between object and function pointer is not supported at all. – user17732522 Oct 09 '22 at 07:56
  • By using the `reinterpret_cast` form, you can ensure that when your codebase drops support for C++03 the clearer form is retained. I'd have thought that even a C++03 compiler should support the C-style cast (to support C-compiled-as-C++), but I've more or less forgotten how such archaic compilers tended to work. – ecatmur Oct 09 '22 at 08:17