Re: [问题] C# 使用C产生的DLL

楼主: fo40225   2015-12-09 22:05:41
※ 引述《hardman1110 (笨小孩)》之铭言:
: 用侦错模式(F5)跑到dll中的function时会出现以下错误:
: Managed Debugging Assistant 'PInvokeStackImbalance'
: has detected a problem in
: 'D:\test_code\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.vshost.exe'.
: wsFormsApplication1.vshost.exe'
: Additional information: 对 PInvoke 函式 'WindowsFormsApplication1!
想知道 stdcall cdecl 代表什么 请Google "x86 calling convention"
就会有非常多文章讲解 在这边不另外说明
直接讲结论
C/C++的标准为 cdecl 这是Visual Studio build C++的默认值
Win32API的标准为 stdcall 这是C# DllImport在x86的默认值
.net 4.0以前(不含) 就算没指定cdecl CLR会纠正错误 但会造成效能上的损失
.net 4.0之后 这项功能因为效能考量被关闭了
https://msdn.microsoft.com/zh-tw/library/ff361650.aspx#Anchor_1
如果需要在.net 4.0之后使用自动修正
在config档加上
<configuration>
<runtime>
<NetFx40_PInvokeStackResilience enabled="1"/>
</runtime>
</configuration>
而 Visual Studio 2010 之后也在在侦错模式下的managed debugging assistant
跳出pInvokeStackImbalance这个错误提示 好让写程式的人知道这个地方有问题
修改方式为
[DllImport("Win32Project1.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
或是C++中函式的宣告改为
extern "C" __declspec(dllexport) int __stdcall Add(int a, int b)
两种选一种即可

Links booklink

Contact Us: admin [ a t ] ucptt.com