BadImageFormatException: Attempting to use a C++ DLL file in C#?

1

Win32 C++ DLL project is saved in my bin/Debug file with the other DLLs.

Running Debug x86 mode on my C# project.

From previous attempts to solve this problem I have changed the Build Configuration to x86 from x64 but I still receive the same error.

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);
        }
    }
}

I created a DLL project in Visual studio. This is my main DLL 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;

}

I am receiving this error message which I do not understand:

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)

'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).

Error after adding extern to C++ function:

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.'

c#
c++
dll
x86
asked on Stack Overflow Jan 28, 2020 by colinodowd • edited Jan 29, 2020 by Andreas Wenzel

1 Answer

1

In x86 (in contrast to x64), there are different calling conventions. The language C (and extern "C" in C++) defaults to the cdecl calling convention, whereas C# defaults to the stdcall calling convention. Therefore, you must set the calling convention to cdecl in C#, like this:

[DllImport("MySimpleLib.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern int AddNumber(int a, int b);
answered on Stack Overflow Jan 28, 2020 by Andreas Wenzel

User contributions licensed under CC BY-SA 3.0