Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load function with dlsym() without reinterpret_cast?

Tags:

c++

clang-tidy

I'm trying to use clang-tidy to enforce the C++ Core Guidelines. While it does have a lot of valid points, there is one thing I cannot really work around: dlsym returns a void* which I need to turn into a proper function pointer somehow. To do that I use reinterpret_cast. Since the guidelines forbid it, I have warnings about it. Of course I can put //NOLINT comments everywhere, but I'm looking for a solution that doesn't use reinterpret_cast so the warnings go away.

Are there any workarounds for this problem?

like image 707
Calmarius Avatar asked Mar 26 '19 17:03

Calmarius


1 Answers

There is no other way in the language to cast a function pointer type to an object pointer type except for reinterpret_cast. Doing so is implementation-defined behavior [expr.reinterpret.cast]/8:

Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value.

That means that a conforming C++ compiler must document if it does not support this feature. And, if it does support it, it must document how exactly it behaves. You can rely on it working (or not being available) in the documented way on that compiler.

Concerning the Core Guidelines linting: If you would have to put //NOLINT "everywhere", then that would seem to imply that you're calling naked dlsym() in many places. Consider wrapping it, for example

template <typename T>
inline T* lookupSymbol(void* module, const char* name)
{
    auto symbol = reinterpret_cast<T*>(dlsym(module, name));  // NOLINT

    if (!symbol)
        throw std::runtime_error("failed to find symbol '"s + name + '\'');

    return symbol;
}
like image 117
Michael Kenzel Avatar answered Nov 04 '22 09:11

Michael Kenzel