Search code examples
c++castingpointer-arithmetic

C++: Alternative to using cast for GetProcAddress() with pointer arithmetic


I have a specific question about the use of GetProcAddress().
My IDE grumbles at the usual way that the cast is not ideal. So alternatively I wrote it with pointer arithmetic.

Now my question is if this is a bad idea? It works that way anyway.

HMODULE Lib = LoadLibrary(L"...");

The common practice

ILibBase* (*p)() = reinterpret_cast<ILibBase* (*)()>(GetProcAddress(Lib, "dllName"));

Pointer arithmetic

ILibBase* base = nullptr;
base += GetProcAddress(Lib, "dllName")() / 8ull;

Solution

  • It is bad idea since (a) pointer size isn't always 8 and (b) actually pointer arithmetic with functions can be silly. (on older systems)

    I suggest

    typedef ILibBase* (*pointer_type)();
    void *func_ptr = GetProcAddress(...); // cast of function to void *
    pointer_type func = reinterpret_cast<pointer_type>(func_ptr); // void * to func