C# cdecl
and C __stdcall
Reasons for coexistence in P/Invoke
In P/Invoke interoperability between C# and C, it is often the case that C# functions use the cdecl
calling convention, while their C corresponding functions use the __stdcall
signature. This mismatch stems from the call convention selection that has been historically continued to this day.
__stdcall
: The caller of Windows function cleans up
__stdcall
inherits from the 16-bit Pascal calling convention and is the default calling convention for Windows API functions and COM. It specifies that the callee (the function being called) cleans the stack after execution, making it more compact in resource-constrained environments. However, if the number of parameters expected by the caller and the callee does not match, this advantage poses the risk of stack imbalance.
__cdecl
: Caller cleaning of mutable parameter function
__cdecl
is a standard calling convention in C for functions with variable number of parameters, such as printf()
and scanf()
. This convention puts the responsibility for stack cleaning on the caller, because the caller knows the number of parameters passed. Forgot to specify CallingConvention.Cdecl
in the [DllImport]
declaration in C# is a common pitfall.
__thiscall
: Hide this pointer of C method
__thiscall
specifically refers to C, which handles passing hidden this
pointers in the instance method of the class. It's similar to __cdecl
, but the .NET P/Invoke marshalling handler does not support it and is therefore not suitable for pinvoke C code.
Summarize
The coexistence of thecdecl call in
in C# and the __stdcall
signature in C is the result of these historical calling conventions and each language-specific requirements. The proper understanding of these conventions, as well as the EntryPoint
and ExactSpelling
properties of are critical to ensuring the correct P/Invoke functionality and avoiding potential issues such as stack imbalance.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3