[英]Calling c++ DLL from C# Program, unhandled exception
我已经做了很多搜索和测试,但无法使它正常工作。 我正在使用MVS Express 2013,正在编译希望从ac#GUI调用的c ++ win32 DLL。
在C ++方面,我已经导出了一个函数,并且该函数传递了一个结构。 该结构最初包含两个字符串,但传递已知大小的char数组似乎更容易。
C ++代码:
struct runDetails{
char requestedRuntype[32];
char filename[32];
};
void __declspec(dllexport) WindowRecreatorCall(runDetails* incomingRunRequests);
C#代码:
尝试重新创建要传递的Struct:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
public struct runDetails{
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)]
public string requestedRuntype;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)]
public string filename;
};
设置动态DLL包装器:
class CallWindowRecreator
{
[DllImport("WindowRecreatorDLL.dll", EntryPoint = "WindowRecreatorCall", CharSet = CharSet.Unicode)]
public static extern void WindowRecreatorCall(ref runDetails runDetails);
};
实际调用DLL:
runDetails testing;
testing.requestedRuntype = "Minimize";
testing.filename = "";
CallWindowRecreator.WindowRecreatorCall(ref testing);
目前,尝试DLL调用时出现此错误:
WindowRecreatorGUI.exe中发生类型为'System.BadImageFormatException'的未处理的异常
附加信息:试图加载格式错误的程序。 (来自HRESULT的异常:0x8007000B)
我做了很多谷歌搜索和代码更改,并且学到了很多东西,但是我只是想不通。 任何提示将非常感谢。
编辑:更改代码并收到错误
编辑2:我已经将C#程序从Any CPU更改为专门用于x86,现在出现此错误:
WindowRecreatorGUI.exe中发生类型为'System.EntryPointNotFoundException'的未处理异常
附加信息:在DLL“ WindowRecreatorDLL.dll”中找不到名为“ WindowRecreatorCall”的入口点。
并在睡前编辑3:
我在c ++函数周围添加了extern c {}。 现在我得到这个错误:
托管调试助手“ PInvokeStackImbalance”已在“ C:\\ Users \\ Tom \\ workspace \\ WindowRecreatorGUI \\ WindowRecreatorGUI \\ bin \\ x86 \\ Debug \\ WindowRecreatorGUI.vshost.exe”中检测到问题。
附加信息:对PInvoke函数'WindowRecreatorGUI!WindowRecreatorGUI.CallWindowRecreator :: WindowRecreatorCall'的调用已使堆栈不平衡。 这可能是因为托管PInvoke签名与非托管目标签名不匹配。 检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。
您的本机方法需要一个指向该结构的指针。
在C#中,这成为ref
参数:
[DllImport("WindowRecreatorDLL.dll", EntryPoint = "WindowRecreatorCall", CharSet = CharSet.Unicode)]
public static extern void WindowRecreatorCall(ref runDetails runDetails);
您还需要在属性(可能是Cdecl
传递正确的CallingConvention
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.