C# Language Calling conventions


Example

There're several conventions of calling functions, specifying who (caller or callee) pops arguments from the stack, how arguments are passed and in what order. C++ uses Cdecl calling convention by default, but C# expects StdCall, which is usually used by Windows API. You need to change one or the other:

  • Change calling convention to StdCall in C++:

    extern "C" __declspec(dllexport) int __stdcall add(int a, int b)
    
    [DllImport("myDLL.dll")]
    
  • Or, change calling convention to Cdecl in C#:

    extern "C" __declspec(dllexport) int /*__cdecl*/ add(int a, int b)
    
    [DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
    

If you want to use a function with Cdecl calling convention and a mangled name, your code will look like this:

__declspec(dllexport) int add(int a, int b)
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl,
           EntryPoint = "?add@@YAHHH@Z")]
  • thiscall(__thiscall) is mainly used in functions that are members of a class.

  • When a function uses thiscall(__thiscall) , a pointer to the class is passed down as the first parameter.