title: BadImageFormatException: Attempting to use a C++ DLL file in C#?
body: <p>Win32 C++ DLL project is saved in my bin/Debug file with the other DLLs.</p>
  
  <p>Running Debug x86 mode on my C# project.</p>
  
  <p>From previous attempts to solve this problem I have changed the Build Configuration to x86 from x64 but I still receive the same error.</p>
  
  <pre><code>namespace ComputerToArduino
  {
      public partial class Form1 : Form
  
      {
  
          [DllImport("MySimpleLib.dll", CharSet = CharSet.Unicode)]
          public static extern int AddNumber(int a, int b);
  
          public Form1()
          {
              InitializeComponent();
              disableControlsArduino();
              disableControlsMotor();
              getAvailableComPorts();
              chartInit();
  
              int result = AddNumber(1, 2);
              Console.Write(result);
          }
      }
  }
  </code></pre>
  
  <p>I created a DLL project in Visual studio. This is my main DLL code:</p>
  
  <pre><code>// dllmain.cpp : Defines the entry point for the DLL application.
  #include "pch.h"
  extern "C" __declspec(dllexport) int AddNumber(int n1, int n2);
  
  
  BOOL APIENTRY DllMain( HMODULE hModule,
                         DWORD  ul_reason_for_call,
                         LPVOID lpReserved
                       )
  {
      switch (ul_reason_for_call)
      {
      case DLL_PROCESS_ATTACH:
      case DLL_THREAD_ATTACH:
      case DLL_THREAD_DETACH:
      case DLL_PROCESS_DETACH:
          break;
      }
      return TRUE;
  }
  
  int AddNumber(int n1, int n2)
  {
  
      return n1 + n2;
  
  }
  
  </code></pre>
  
  <p>I am receiving this error message which I do not understand:</p>
  
  <blockquote>
    <p>Exception thrown: 'System.BadImageFormatException' in ComputerToArduino.exe
    An unhandled exception of type 'System.BadImageFormatException' occurred in ComputerToArduino.exe
    An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)</p>
    
    <p>'ComputerToArduino.exe' (CLR v4.0.30319: ComputerToArduino.exe): Loaded 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Remote Debugger\x64\Runtime\Microsoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
    The program '[14748] ComputerToArduino.exe' has exited with code -1 (0xffffffff).</p>
  </blockquote>
  
  <p>Error after adding extern to C++ function:</p>
  
  <p>Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'ComputerToArduino!ComputerToArduino.Form1::AddNumber' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'</p>