【发布时间】:2019-08-04 17:35:13
【问题描述】:
我认为以下两段代码应该是等价的:
// first example
string s = "Hello memmory";
ReadOnlyMemory<char> memory = s.AsMemory();
using (MemoryHandle pin = memory.Pin())
{
Span<char> span = new Span<char>(pin.Pointer, 1);
Console.WriteLine(span[0]);
}
// second example
ReadOnlySpan<char> span2 = memory.Span;
Console.WriteLine(span2[0]);
两个代码都将打印“H”。
我不明白的是第二个示例中的内存取消固定在哪里。
据我了解,字符串是在堆上分配的,MemoryHandle 固定它并从指针创建 Span。 MemoryHandle.Dispose 取消固定内存。
我相信memory.Span 也必须固定内存,否则 span 无法访问指针。但是第二个例子中的内存是如何取消固定的呢?
【问题讨论】:
标签: c# memory-management heap-memory