what does CALLBACK do?

When I declare a callback like
  LRESULT WndProc(...)

and i make a conversion like this
 wcex.lpfnWndProc = (WNDPROC) WndProc;

my application crashes after the window destroying.

but the following can work well.

 wcex.lpfnWndProc = WndProc;

why is that? i thought they are the same.
what does CALLBACK do?
Last edited on
wcex.lpfnWndProc = (WNDPROC) WndProc;
The fact that you need to cast is indicating your callback has the wrong signature or calling convention.

The cast means, "Ignore the mismatch, I'm right, I'll take responsibility for it." In other words, a cast overrides the type system.
CALLBACK is specifying the calling convention to use.

Calling convention

CALLBACK is acually a #define of __stdcall

If you don't tell the compiler otherwise (by using an explicit calling convention or a command line switch) then the compiler will use __cdecl. So your first version is actually

LRESULT __cdecl WndProc(...)

Part of the calling convention is who cleans up the stack. In the __cdecl case, the called function cleans the stack up before it returns. In the __stdcall case, the caller cleans it up after the function returns.

If you call a __cdecl function as if it was __stdcall then the stack clean-up will get messed up and you program will have problems!

For this reason you should never use a WNDPROC cast as you are above, or do a similar thing with other function pointer types.


x86 calling conventions

The history of calling conventions, part 3

Calling Conventions
Last edited on
Topic archived. No new replies allowed.