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.
 
  LRESULT CALLBACK WndProc(...)

 
 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
http://en.wikipedia.org/wiki/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.

Andy

x86 calling conventions
http://en.wikipedia.org/wiki/X86_calling_conventions

The history of calling conventions, part 3
http://blogs.msdn.com/b/oldnewthing/archive/2004/01/08/48616.aspx

Calling Conventions
http://msdn.microsoft.com/en-us/library/k2b2ssfy%28v=vs.100%29.aspx
Last edited on
Topic archived. No new replies allowed.