title: Why are Cdecl calls often mismatched in the "standard" P/Invoke Convention?
body: <p>I am working on a rather large codebase in which C++ functionality is P/Invoked from C#.</p>
  
  <p>There are many calls in our codebase such as...</p>
  
  <p>C++:</p>
  
  <pre><code>extern "C" int __stdcall InvokedFunction(int);
  </code></pre>
  
  <p>With a corresponding C#:</p>
  
  <pre><code>[DllImport("CPlusPlus.dll", ExactSpelling = true, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
      private static extern int InvokedFunction(IntPtr intArg);
  </code></pre>
  
  <p>I have scoured the net (insofar as I am capable) for the reasoning as to why this apparent mismatch exists.  For example, why is there a Cdecl within the C#, and __stdcall within the C++?  Apparently, this results in the stack being cleared twice, but, in both cases, variables are pushed onto the stack in the same reverse order, such that I do not see any errors, albeit the possibility that return information is cleared in the event of attempting a trace during debugging?</p>
  
  <p>From MSDN:  <a href="http://msdn.microsoft.com/en-us/library/2x8kf7zx%28v=vs.100%29.aspx">http://msdn.microsoft.com/en-us/library/2x8kf7zx%28v=vs.100%29.aspx</a></p>
  
  <pre><code>// explicit DLLImport needed here to use P/Invoke marshalling
  [DllImport("msvcrt.dll", EntryPoint = "printf", CallingConvention = CallingConvention::Cdecl,  CharSet = CharSet::Ansi)]
  
  // Implicit DLLImport specifying calling convention
  extern "C" int __stdcall MessageBeep(int);
  </code></pre>
  
  <p>Once again, there is both <code>extern "C"</code> in the C++ code, and <code>CallingConvention.Cdecl</code> in the C#.  Why is it not <code>CallingConvention.Stdcall</code>?  Or, moreover, why is there <code>__stdcall</code> in the C++?</p>
  
  <p>Thanks in advance!</p>