Why traditional GetProcAddress to std::function is not working straightforward

0

As in the title I'd like to convert GetProcAddress into std::function. Yes, there are multiple solutions in stack overflow, but none actually explains why those workarounds are needed. I can't really understand the exact error message and why it happens. The sample source is simple:

#include <functional>
#include <Windows.h>

using fn_NtAllocateVirtualMemory = NTSTATUS (NTAPI*)(
        HANDLE      ProcessHandle,
        PVOID*      BaseAddress,
        ULONG_PTR   ZeroBits,
        PSIZE_T     RegionSize,
        ULONG       AllocationType,
        ULONG       Protect
    );

int main()
{
    std::function<fn_NtAllocateVirtualMemory> myFn(reinterpret_cast<fn_NtAllocateVirtualMemory>(0xDEADBABE));
}

( https://godbolt.org/z/FhaeLA )

So, my question is why is it wrong?


Related: I also tried this: Function pointer to multiple argument C++11 std::function: Templating GetProcAddress But it also failed to compile ( https://godbolt.org/z/1wSDZj )

I've also found this topic: C++ Dynamically load arbitrary function from DLL into std::function Which might work (I haven't yet tried, I'll do it soon) but I'm trying to understand why this kind of cryptic looking huge boilerplate is necessary.


Notes:

  • Obviously 0xDEADBEEF is going to be replaced with the necessary address.
  • I'm using Visual Studio 2019 to compile, but obviously any generic answer is welcomed
c++
c++17
dynamic-import
asked on Stack Overflow Apr 17, 2019 by original.roland

1 Answer

5

std::function takes signature as template parameter, not pointer.

So it should be:

using fn_NtAllocateVirtualMemory = NTSTATUS NTAPI (
        HANDLE      ProcessHandle,
        PVOID*      BaseAddress,
        ULONG_PTR   ZeroBits,
        PSIZE_T     RegionSize,
        ULONG       AllocationType,
        ULONG       Protect
    );

int main()
{
    std::function<fn_NtAllocateVirtualMemory> myFn(
        reinterpret_cast<fn_NtAllocateVirtualMemory*>(0xDEADBABE));
}
answered on Stack Overflow Apr 17, 2019 by Jarod42 • edited Apr 18, 2019 by Jarod42

User contributions licensed under CC BY-SA 3.0