在 C# .NET 上使用非托管内存跨度在 Ubuntu 中无法按预期工作

分享于2022年11月29日 .net arrays c# memory 问答
【问题标题】:Working with Span of Unmanaged memory on C# .NET do not work as expected in Ubuntu在 C# .NET 上使用非托管内存跨度在 Ubuntu 中无法按预期工作
【发布时间】:2022-11-28 07:59:09
【问题描述】:

我有一个使用 .Net Marshal Class 的非托管内存(本机堆)的简单示例,如下所示。

const int nbytes = 100;
    var ptr = Marshal.AllocHGlobal(nbytes);
    try
    {
        var ptrToInt = (int*)ptr.ToPointer();// We should cast void* to int*
        Span span = new Span(ptrToInt, nbytes >> 2);
        span.Fill(42);
        int cap = nbytes >> 2;
        for (int i = 0; i < cap; i++)
        {
            Console.WriteLine(span[i]);

        }
        Console.WriteLine(",", string.Join(",", span.ToArray())); // This does not work and I do not know why?!
    }
    finally
    {
        Marshal.FreeHGlobal(ptr);// We should free memory we used at the end
    }

这里的要点是,跨度的 ToArray 方法不起作用,而我按索引遍历跨度索引时效果很好。这背后的原因是什么?托管内存的跨度效果很好,所以我认为这里有一些我不知道/考虑的跨度 谢谢


【解决方案1】:

查看代码中的警告:

解决方案:

Console.WriteLine("{0}", string.Join(",", span.ToArray()));

结果:

【讨论】: