henk
henk

Reputation: 1

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?

Upvotes: 0

Views: 93

Answers (1)

Blindy
Blindy

Reputation: 67380

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

Upvotes: 3

Related Questions