BadImageFormatException:试图在C#中使用C ++ DLL文件?

问题描述 投票:1回答:1

Win32 C ++ DLL项目与其他DLL保存在我的bin / Debug文件中。

在我的C#项目上运行Debug x86模式。

从以前尝试解决此问题的尝试,我已将构建配置从x64更改为x86,但仍然收到相同的错误。

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

我在Visual Studio中创建了一个DLL项目。这是我的主要DLL代码:

// 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;

}

我收到我不理解的错误消息:

抛出异常:ComputerToArduino.exe中的'System.BadImageFormatException'ComputerToArduino.exe中发生类型为'System.BadImageFormatException'的未处理异常试图加载格式错误的程序。 (来自HRESULT的异常:0x8007000B)

''ComputerToArduino.exe'(CLR v4.0.30319:ComputerToArduino.exe):已加载'C:\ Program Files(x86)\ Microsoft Visual Studio \ 2019 \ Community \ Common7 \ IDE \ Remote Debugger \ x64 \ Runtime \ Microsoft。 VisualStudio.Debugger.Runtime.dll”。跳过的加载符号。模块已优化,调试器选项“ Just My Code”已启用。程序“ [14748] ComputerToArduino.exe”已退出,代码为-1(0xffffffff)。

将extern添加到C ++函数后出错:

托管调试助手'PInvokeStackImbalance':'对PInvoke函数'ComputerToArduino!ComputerToArduino.Form1 :: AddNumber'的调用已使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。'

Win32 C ++ DLL项目与其他DLL保存在我的bin / Debug文件中。在我的C#项目上运行Debug x86模式。通过先前解决该问题的尝试,我更改了Build Configuration ...

c# c++ dll x86
1个回答
0
投票

在x86中(与x64相反),有不同的调用约定。语言C(和C ++中的外部“ C”)默认为cdecl调用约定,而C#默认为stdcall调用约定。因此,必须在C#中将调用约定设置为cdecl,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.