gpt4 book ai didi

c# 如果 span(memory) 引用堆栈上的缓冲区会发生什么

转载 作者:行者123 更新时间:2023-11-30 15:52:53 25 4
gpt4 key购买 nike

.NET Standard 2.1 引入了一项新功能,您可以在其中“控制”内存块而不是复制它们:SpanMemory .

在文档示例中,我注意到可以引用堆栈缓冲区:

byte data = 0;
Span<byte> stackSpan = stackalloc byte[100];
for (int ctr = 0; ctr < stackSpan.Length; ctr++)
stackSpan[ctr] = data++;

据我所知,进程的堆栈内存是有限的(1MB或4MB),我们无法手动释放它。

所以我想创建一个 Memory<T>Span<T>会以某种方式“固定”堆栈上的内存位置,以便我们可以对其进行索引吗?但这不会是可能导致堆栈溢出的潜在堆栈泄漏案例吗?由于堆栈上的数组应该与 Memory<T> 一样长或 Span<T> .

最佳答案

这是安全的,因为 Span 的生命周期与堆栈分配的数组相同或更短。

您不能分配 stackalloc 的结果至 Memory<T>至少直接(我认为即使是不安全的代码也无济于事 - C#: convert generic pointer to array )所以将其范围限定为 Span<T> .

根据link您发布的 Span lifetime is tied to scope it defined:

Span<T> is a ref struct that is allocated on the stack rather than on the managed heap. Ref struct types have a number of restrictions to ensure that they cannot be promoted to the managed heap,

请注意 ref struct禁止某些操作,包括您应该关注的操作 - 返回 Span<T>来自分配堆栈的方法。结果 span 将同时(或更早)被销毁,然后堆栈框架包括由 stackalloc 创建的数组.

   static Span<byte> MySpan()
{
Span<byte> span = stackalloc byte[100];
// error CS8352: Cannot use local 'span' in this context because it may
// expose referenced variables outside of their declaration scope
return span;
}

MSDN 杂志文章(2018 年 1 月)也对此进行了介绍 C# - All About Span: Exploring a New .NET Mainstay Stephen Toub 着。

关于c# 如果 span<T>(memory<T>) 引用堆栈上的缓冲区会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53574248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com