3

I was looking at some code like the one mentioned here: Function pointers for winapi functions (stdcall/cdecl), Function pointer and calling convention, etc.

What is the need, benefit for declaring the calling type of a function pointer as __stdcall?

Why declare the calling type for a function pointer at all?

Community
  • 1
  • 1
armundle
  • 1,149
  • 2
  • 15
  • 28
  • 2
    Function pointers aren't very useful if you can't call the function using them. If the compiler doesn't know what ABI the function expects, it can't call the function. – Stephen Canon Nov 05 '14 at 20:29
  • Well, create a program that declares a function as __cdecl, and declare the pointer to the function as __stdcall. Give the function a couple of parameters (maybe and `int` and a `double`). Create a function pointer and call the function. Come back to SO when your program keeps crashing on the call. – PaulMcKenzie Nov 05 '14 at 20:41
  • 1
    See also: [What can go wrong when you mismatch the calling convention?](http://blogs.msdn.com/b/oldnewthing/archive/2004/01/15/58973.aspx) – Adam Rosenfield Nov 06 '14 at 03:51

1 Answers1

3

Embedding a calling convention specifier in a function pointer allows you to use that calling convention when calling functions through that pointer. __stdcall is the calling convention used to call Win32 API functions.

The benefit of specifying it in a function pointer is being able to match a different calling convention according to your code's needs (e.g. when loading an external library's function via late binding). Library headers should specify them as a good programming practice.

There's a caveat though: if you embed a wrong calling convention in a function pointer, the compiler might be powerless to help you detect that and you might end up doing bad things at runtime.

Marco A.
  • 43,032
  • 26
  • 132
  • 246