是否可以在没有固定<T>表达式的情况下指向固定大小的缓冲区?



我正在使用。NET Core 2.1和语言标准7.3。我希望引用一个固定缓冲区,而不获取指向它的指针。目前可能吗?

public unsafe struct InteropStruct
{
private fixed byte dataField[32];
public Span<byte> Data
{
get
{
//return a span referencing the private field without a fixed statement
}
}
}

我知道Span目前能够通过垃圾收集来跟踪托管数组,所以我看不出有任何东西阻止它以类似的方式跟踪固定缓冲区。

如果这不可能,如果我真的使用这样一个固定的语句会发生什么:

public unsafe struct InteropStruct
{
private fixed byte dataField[32];
public Span<byte> Data
{
get
{
fixed (byte* ptr = dataField)
{
return new Span<byte>(ptr, 32);
}
}
}
}

如果结构被封装在堆上的对象或类中,垃圾收集器会成为问题吗?

所以,我以ILSpy'ing的形式做了一些研究。NET程序集,以及上的一些测试。NET核心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框架的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字段模型,它的指针将不会更新。原因是什么?3字段跨度的Span<T>(void* pointer, int length)构造函数(我正在使用它)使用pointer参数设置_byteOffset字段。GC将更新的3字段跨度中的指针是_pinnable字段。对于2字段"跨度",它们是相同的。

所以,我的问题的答案是,是的,无论是否使用固定语句,我都可以将Span点指向固定缓冲区,但在不使用时这样做是危险的。NET Core的2字段跨度模型。如果我说错了,请纠正我。NET Framework当前的Span模型。

相关内容

最新更新