C# - 如何在包含数组的结构中编组非托管结构
C# - How to marshal an unmanaged struct within a struct that contains arrays
我的任务是将 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;
}
终于让它正常工作了,所以我会 post 为任何可能觉得它有用的人提供帮助。
[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;
我的任务是将 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;
}
终于让它正常工作了,所以我会 post 为任何可能觉得它有用的人提供帮助。
[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;