5

我正在尝试在课堂上使用该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;
    }

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

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

我收到如下错误:

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

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

4

2 回答 2

2

作为此问题的解决方法,您可以使用MemoryMappedViewStream而不是 MemoryMappedViewAccessor;然后在其上使用传统的流读/写而不是访问器。

于 2012-10-20T23:14:07.577 回答
0

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

于 2012-10-15T18:36:43.220 回答