指定的类型必须是不包含引用的结构

GWL*_*osa 5 .net c# structure exception memory-mapped-files

我正在尝试Write<T>MemoryMappedViewAccessor课堂上使用该功能。我T在这种情况下如下:

[StructLayout(LayoutKind.Explicit)]
    public struct Message
    {
        public void AddString(string str)
        {
            if (stringContents == null)
                stringContents = new byte[1024 * 10];
            stringContents = Encoding.ASCII.GetBytes(str);
        }
        public string GetString()
        {
            if (stringContents == null)
                return string.Empty;
            return Encoding.ASCII.GetString(stringContents);
        }
        [FieldOffset(0)]
        public byte[] stringContents;
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我拨打电话时,例如:

//Initialized Elsewhere: MemoryMappedViewAccessor writer
Message messageAlreadyOnWire = new Message();
messageAlreadyOnWire.AddString(data);
writer.Write<Message>(0, ref messageAlreadyOnWire);
Run Code Online (Sandbox Code Playgroud)

我收到如下错误:

指定的类型必须是不包含引用的结构。参数名称:类型

我的结构中唯一的“引用”是一个字节数组。有没有办法解决这个问题?我对固定长度的字节数组没问题,但我不确定如何在不深入研究 的情况下声明一个unsafe,我不想这样做。

Den*_*nis 0

尝试申请[MarshalAs(UnmanagedType.ByValArray, SizeConst = Your_Size)]Message.stringContents.