C#:编组包含重新访问的数组的结构

问题描述

我正在尝试执行包含数组的结构的 Marshal.SizeOf(msg) :

    [StructLayout(LayoutKind.Sequential,Pack = 1)]
    public unsafe struct ServiceMsg
    {
        public byte start;
        public byte type;
        public byte length;
        [MarshalAs(UnmanagedType.ByValArray,SizeConst = ServiceMsgWrap.MaxPayload,ArraySubType = UnmanagedType.U1)]
        public fixed byte payload[ServiceMsgWrap.MaxPayload];
        public UInt16 crc;
    }

...

    Protocol.ServiceMsg msg = new Protocol.ServiceMsg();
    length = Marshal.SizeOf(msg);

但我得到一个运行时异常:“不能作为未处理的结构进行编组”。如果我删除有效负载,它会起作用.... 我错过了什么?

解决方法

你在混淆概念。要么让编组器完成其工作,即将您的托管结构与本机代码进行编组,要么完全接管(使用您的 fixed 语句)。

使用编组器的正确 C# 结构是这样的:

[StructLayout(LayoutKind.Sequential,Pack = 1)]
public struct ServiceMsg
{
    public byte start;
    public byte type;
    public byte length;
    [MarshalAs(UnmanagedType.ByValArray,SizeConst = ServiceMsgWrap.MaxPayload,ArraySubType = UnmanagedType.U1)]
    public byte[] payload;
    public ushort crc;
}