固定后的 C# 内存和垃圾收集器

C# memory after fixed and the Garbage Collector

我正在使用 BinaryReader.Read 从二进制文件中读取字节,并使用 fixed 语句将字节 'convert' 放入结构中:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct MyStruct
{
    // some variables.. too many to list
    public fixed Byte Software[32];
    public UInt16 FC_Day;
    public UInt16 FC_Year;
    public UInt16 Header_Size; 
    public UInt32 Offset_to_Data;
    // more variables.. too many to list
};

然后在 Main 中:

byte[] ReadBytes = new byte[227];
MyStruct* Header;
InFile.Read(ReadBytes, 0, 227);
fixed (byte* bHdrPtr = &ReadBytes[0])
{
    Header = (LASHeader*)bHdrPtr;
    //now Header and ReadBytes occupy the same memory
}

此时对 ReadBytes 的任何更改都会更改 Header,反之亦然。据我了解,fixed 语句使指针免于在 fixed 块中移动,但是结构和字节现在 永久 会占用相同的内存还是会内存管理move/shuffle地址分开?即我可以相信 fixed 块之后的结构指向相同的有意义的内存,而不是变成随机字节或全 0 吗?

之前我声明了 bytes[227]MyStruct 并使用 Buffer.BlockCopy 将字节从数组复制到结构中。这是非常低效的,需要双倍的内存和每次读取新字节时的块副本,所以我更愿意像我在 C++ 中所做的那样重铸字节以节省内存并希望加快进程。

but will the structure and bytes now permanently occupy the same memory

docs fixed 状态:

After the code in the statement is executed, any pinned variables are unpinned and subject to garbage collection. Therefore, do not point to those variables outside the fixed statement. The variables declared in the fixed statement are scoped to that statement

因此,不 - 更改不是 永久性的 - 它的范围 fixed 语句内。