简体   繁体   English

C#:重新编组包含 arrays 的结构

[英]C#: marshalling a struct that contains arrays revisited

Im trying to do Marshal.SizeOf(msg) of a struct containing an array:我正在尝试对包含数组的结构执行 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);

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).要么让编组器完成它的工作,即将你的托管结构编组到本机代码,要么完全接管(使用你的fixed语句)。

A proper C# structure that uses the marshaller is this:使用编组器的正确 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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