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