I was looking through some code from the SDL library and came across a function declared like this:
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
Now, I'm a Delphi coder. No hablo C muy bien, senor. But I remember enough syntax from my college courses to read it like this:
Function name is WndProc. Argument list is pretty self-explanatory. Function return type is LRESULT. But what in the world is that "CALLBACK" doing there? In Delphi, any function can be used as a callback; you just need to pass the right type of function pointer. Is there any particular reason why C doesn't work that way? Or does it mean something different?
It's the calling convention. It's required when you pass a pointer to this function to a Windows API which later calls that function. The Windows calling convention is different from the C calling convention, therefore you need to specify to the compiler that WndProc() is special, and that it needs different startup and cleanup code.
It's a calling convention, and Delphi has them too. Try looking up 'cdecl' in the Delphi Help. In Delphi (or Object Pascal as we oldies like to call it) calling conventions come after the function declaration, like this;
The "CALLBACK" is a calling convention. There are other kinds of calling conventions. CALLBACK is the same as __stdcall.
http://www.codeguru.com/cpp/cpp/cpp_mfc/callbacks/article.php/c10557
Some more information at Raymond Chen's blog:
http://blogs.msdn.com/oldnewthing/archive/2004/01/08/48616.aspx
Short roundup from Raymond Chen's Blog:
C calling convention (__cdecl)
The C calling convention is constrained because it allows the use of functions with a variable number of parameters. It pretty much requires that the stack be caller-cleaned and that the parameters be pushed right to left, so that the first parameter is at a fixed position relative to the top of the stack. In summary: Caller cleans the stack, parameters pushed right to left.
Pascal calling convention (__pascal)
Pascal does not support functions with a variable number of parameters, so it can use the callee-clean convention. Parameters are pushed from left to right. Nearly all Win16 functions are exported as Pascal calling convention. The callee-clean convention saves three bytes at each call point, with a fixed overhead of two bytes per function. It was also fractionally faster. On Win16, saving a few hundred bytes and a few cycles was a big deal. Note: The Fortran calling convention (__fortran) is the same as the Pascal calling convention