简体   繁体   中英

C#: marshalling a struct that contains arrays revisited

Im trying to do Marshal.SizeOf(msg) of a struct containing an array:

    [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);

But I get a runtime exeption: "cannot be marshaled as an unhandled structure". If I remove the payload it works.... What am I missing?

You're mixing concepts. Either let the marshaller do its job, ie to marshal your managed structure to and from native code, or take over completely (with your fixed statement).

A proper C# structure that uses the marshaller is this:

[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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM