Search code examples
c++castingreinterpret-cast

Application crashes, pointer to function is suspect


I have the following code:

#include <windows.h>
class systemfunctions
{
    public:
    void (*sleep) (DWORD ms);

    systemfunctions ()
    {
        sleep = reinterpret_cast<void>(Sleep);
    }
} sys;

When I call sys.sleep(), the application crashes. Why does the program crash, and what can I do to resolve the problem?


Solution

  • Windows.h declares Sleep() like WINBASEAPI VOID WINAPI Sleep(__in DWORD dwMilliseconds);, try telling the compiler it needs to use the proper calling convention when it uses that pointer:

    typedef VOID (WINAPI * SleepFunction)(DWORD ms);
    SleepFunction sleep;
    
    sleep = Sleep;