我有一个带有这个函数的delphi dll:
function writeRate(data: variant):Double ; stdcall;
我使用此方法从 c# 调用函数:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate double WriteRate(object data);
protected void UpdateRateChannel(string myData)
{
IntPtr pDll = NativeMethods.LoadLibrary("mydll.dll");
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "writeRate");
WriteRate writeRate = (WriteRate)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(WriteRate ));
double response = writeRate(myData);
bool result = NativeMethods.FreeLibrary(pDll);
}
但我得到这个例外:
PInvokeStackImbalance was detected
如何调用 dll?我认为问题出在变体类型中。谢谢!
Delphi 代码中的stdcall
与 C# 中的CallingConvention.StdCall
匹配。您应该修复委托定义。
如果 Delphi 函数被声明为 stdcall
,为什么要在 C# 中将其声明为 cdecl
?
这就是堆栈不平衡的原因。更改 C# 声明以使用 stdcall
约定来匹配 Delphi 声明。
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate double WriteRate(object data);
C# 中的 Variant 可能与 Delphi 中的普通 Variant 不兼容。改用Delphi的OleVariant 。