因此,我以 ILSpy'ing .NET Assemblies 的形式做了一些研究,并对 .NET Core 2.1 进行了一些测试。
我的测试结果如下:
interface ITest
{
Span<byte> Data { get; }
}
unsafe struct TestStruct : ITest
{
fixed byte dataField[8];
public Span<byte> Data
{
get
{
//Unsafe.AsPointer() to avoid the fixed expression :-)
return new Span<byte>(Unsafe.AsPointer(ref dataField[0]), 8);
}
}
}
class Program
{
//Note: This test is done in Debug mode to make sure the string allocation isn't ommited
static void Main(string[] args)
{
new string('c', 200);
//Boxes the struct onto the heap.
//The object is allocated after the string to ensure it will be moved during GC compacting
ITest HeapAlloc = new TestStruct();
Span<byte> span1, span2;
span1 = HeapAlloc.Data; //Creates span to old location
GC.Collect(2, GCCollectionMode.Forced, true, true); //Force a compacting garbage collection
span2 = HeapAlloc.Data; //Creates span to new location
//Ensures that if the pointer to span1 wasn't updated, that there wouldn't be heap corruption
//Write to Span2
span2[0] = 5;
//Read from Span1
Console.WriteLine(span1[0] == 5); //Prints true in .NET Core 2.1, span1's pointer is updated
}
}
我从对 IL 的研究中学到了什么,如果我解释得不正确,请原谅我:
.NET Core 的 2 个字段跨度:
//Note, this is not the complete declaration, just the fields
public ref readonly struct Span<T>
{
internal readonly ByReference<T> _pointer;
private readonly int _length;
}
.NET Framework 3 字段跨度:
//Same note as 2 Field Span
public ref readonly struct Span<T>
{
private readonly Pinnable<T> _pinnable;
private readonly IntPtr _byteOffset;
private readonly int _length;
}
.Net Core正在使用Span的2字段模型。由于.NET Framework使用3字段模型,它的指针不会被更新。原因?这Span<T>(void* pointer, int length)
3 个字段跨度的构造函数(我为此使用的)设置了_byteOffset
场与pointer
争论。 GC 将更新的 3 个字段跨度中的指针是_pinnable
场地。对于 2 个字段 Span,它们是相同的。
所以,我的问题的答案是,是的,我可以使用或不使用固定语句让 Span 指向固定缓冲区,但在不使用 .NET Core 的 2 字段 Span 模型时这样做是很危险的。如果我对 .NET Framework 当前的 Span 模型的理解有误,请纠正我。