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?

3
  • 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. Commented Nov 5, 2014 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. Commented Nov 5, 2014 at 20:41
  • 1
    See also: What can go wrong when you mismatch the calling convention? Commented Nov 6, 2014 at 3:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.