Home > Enterprise >  How do I cast the result of GetProcAddress to a function pointer without -fpermissive on mingw?
How do I cast the result of GetProcAddress to a function pointer without -fpermissive on mingw?

Time:06-29

When I use -fpermissive I can just write something like this:

void (*NtSetTimerResolution)(ULONG, bool, PULONG) = 0;

int main()
{
    NtSetTimerResolution = GetProcAddress(GetModuleHandle("ntdll.dll"), "NtSetTimerResolution");
    ULONG pointless;
    NtSetTimerResolution(0x1388, 1, &pointless);
    return 0;
}

and it compiles and runs just fine with no runtime errors. How can I re-write this code to not include fpermissive?

CodePudding user response:

You need an explicit cast:

NtSetTimerResolution = reinterpret_cast <void (*)(ULONG, bool, PULONG)> (GetProcAddress(GetModuleHandle("ntdll.dll"), "NtSetTimerResolution"));

You might still be violating strict aliasing rules here, but you can use -fno-strict-aliasing to get round that.

  •  Tags:  
  • c
  • Related