title: Calling C DLL from C++ gives Access Violation but C# project with DllImport working
body: <p>I have a 32-bit 3rd party C DLL that I need to integrate with, but am hitting an error that's difficult to understand/track down.</p>
  
  <p>I can compile and successfully link a simple C++ 32-bit app consisting of the following:</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;windows.h&gt;
  
  extern "C" int __stdcall external_method(int cardno);
  
  int main()
  {
      int n = external_method(0);
      return 0;
  }
  </code></pre>
  
  <p>When I try to run the app though in debug mode it gives the following:</p>
  
  <pre><code>Unhandled exception at 0x100AADF5 (ExternalModule.dll) in 
  ConsoleApplication2.exe: 0xC0000005: Access violation reading location 0x00000000.
  </code></pre>
  
  <p>However, if I create a simple C# application that uses DllImport/PInvoke to call the same function it runs fine:</p>
  
  <pre><code>namespace ConsoleApplication3
  {
      class Program
      {
          [DllImport("ExternalModule.dll")]
          public static extern int external_method(int n);
  
          static void Main(string[] args)
          {
              external_method(0);
              Debug.WriteLine("YES!");
          }
      }
  }
  </code></pre>
  
  <p>I'm struggling to understand how one can work and the other fail. Unfortunately I have no access to the developer of the C DLL.</p>
  
  <p>Any help much appreciated.</p>
  
  <p><em>Update</em> Thanks for the comments. Here is the header file entry for the method:</p>
  
  <pre><code>int __stdcall exernal_method(int cardno);
  </code></pre>
  
  <p>Am reasonably sure that the calling convention is ok. The DLL is being loaded because using the debug version of the DLL I can see it output some messages to the debug output before it fails.</p>
  
  <p>Could it be an issue with stack being corrupted on exit of the method? I tried a couple of different calling conventions but this is the only one that the linker was able to work with.</p>