我的任务是将C#程序与带有非托管代码的.DLL连接起来。我在互联网上找不到任何东西来帮助我实现这个目标。我得到一个PInvokeStackImbalance异常。我已经尝试将CallingConvention更改为.Winapi而没有运气。我可能会对此完全错误,所以对于如何处理此问题的任何指导都表示赞赏!
以下是我必须使用的非托管代码:
extern "C" __declspec(dllexport) int WINAPI GetAlarm (unsigned short hndl, ALARMALL *alarm);
typedef struct {
ALARM alarm [ALMMAX];
} ALARMALL;
ALMMAX = 24
typedef struct {
short eno;
unsigned char sts;
char msg[32];
} ZALARM;
以下是我编写的托管C#端:
[DllImport("my.dll", EntryPoint = "GetAlarm", CallingConvention = CallingConvention.Cdecl)]
public static extern int GetAlarm(ushort hndl, ALARMALL alarm);
public struct ALARMALL
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
ZALARM alarm;
}
[StructLayout(LayoutKind.Sequential)]
public struct ZALARM
{
[MarshalAs(UnmanagedType.I2)]
public short eno;
[MarshalAs(UnmanagedType.U1)]
public byte sts;
[MarshalAs(UnmanagedType.I1, SizeConst = 32)]
public char msg;
}
答案 0 :(得分:1)
最后让这个工作正常,所以我会发帖给任何可能觉得有用的人。
[DllImport("my.dll", EntryPoint = "GetAlarm")]
public static extern int GetAlarm(ushort hndl, ref ALARMALL alarm);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct ALARMALL
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
public ZALARM[] alarm;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct ZALARM
{
public short eno;
public byte sts;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string msg;