Question

I have been using PInvoke to let my C# application call C++ functions I wrote.

Now, I keep hearing everywhere and beyond that I need to define those externally accessible functions with the __stdcall convention. My question is: Why?

So far, I have accidentally ignored this advice, and everything works like a charm. When I add __stdcall to my functions, everything keeps working in the same way (or at least it seems so).

This article says that __stdcall is used for Win32 bit functions, but I am compiling against the x64 platform. Does that mean that I shouldn't be using __stdcall after all or does it mean that I am missing out on something else?

And please, use simple English when responding. ;-) Lines like this (quoted from the article I linked):

The callee cleans the stack, so the compiler makes vararg functions __cdecl.

make my brain feel like there's tumbleweed blowing through it.

Was it helpful?

Solution

There is only one calling convention on x64 and so it does not matter which calling convention you specify. It is always ignored on x64.

On x86 it is important to make sure calling conventions match on both sides of the interface. So if you ever anticipate running your code on x86 it would be prudent to get that right now.

OTHER TIPS

Calling conventions are an historical accident in 32-bit code. There is only one convention in 64-bit code so whatever you declare doesn't matter.

If you author an unmanaged 32-bit DLL that might be used by code that wasn't written in C or C++ then declaring your exported function with __stdcall helps reduce accidents. Most language runtimes support interop to allow OS calls so they make __stdcall the default.

You'll find more details about calling conventions and name decoration in this answer

You're missing the fact that x64 and Win32 are totally different things. Win32 is an C API to interact with Windows, and its calling convention is __stdcall, whereas x64 or x86-64 is the size of your CPU registers. (ie 64 bits wide).

In Wikipedia article under x86-64 calling convention:

When compiling for the x64 architecture in a Windows context (whether using Microsoft or non-Microsoft tools), there is only one calling convention — the one described here, so that stdcall, thiscall, cdecl, fastcall, etc., are now all one and the same.

Apparently x64 (AMD) doesn't care about calling conventions, but hope the above clears up some confusion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top