Niklas R
Niklas R

Reputation: 16860

Less writing for type conversion possible?

Let's assume you loaded a dynamic library using dlopen() or LoadLibrary() on Windows, and you want to get a symbol from it and cast it to a specific function type. It is so unbelievable redundant to write the type twice!

void (*Test)(int, float) =
        reinterpret_cast<void (*Test)(int, float)>(dlsym(handle, "Test"));

I want the code to be compilable without the C++11 standard, therefore the auto keyword is not an option. I tried using templates because compilers can often detect the template parameters from the given parameters, but it does not seem to work for the type of the assignment value.

template <typename T>
T GetSym(void* handle, const char* symbol) {
    return (T) dlsym(handle, symbol);
}

void (*Test)(int, float) = GetSym(handle); // does not compile

Is there a way to bring less redundancy into the code? When retrieving a huge number of functions from a dynamically loaded library, it is awful to write each and every cast twice!

Upvotes: 0

Views: 79

Answers (1)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234354

You can do this with an evil templated conversion operator.

struct proxy {
public:
    proxy(void* ptr) : ptr(ptr) {}

    template <typename T>
    operator T() const {
        return reinterpret_cast<T>(ptr);
    }
private:
    void* ptr;
};

proxy GetSym(void* handle, const char* symbol) {
    return proxy(dlsym(handle, symbol));
}

Upvotes: 2

Related Questions