跨度和二维数组 [英] Span and two dimensional Arrays

查看:92
本文介绍了跨度和二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用新的 System.Memory Span结构具有二维数据数组?

Is it possible to use the new System.Memory Span struct with two dimensional arrays of data?

double[,] testMulti = 
    {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 9.5f, 10, 11 },
        { 12, 13, 14.3f, 15 }
    };

double[] testArray = { 1, 2, 3, 4 };
string testString = "Hellow world";

testMulti.AsSpan(); // Compile error
testArray.AsSpan();
testString.AsSpan();

尽管testArray和testString具有AsSpan扩展名,但testMulti不存在此类扩展名.

Whilst testArray and testString have a AsSpan extension, no such extension exists for testMulti.

Span的设计是否仅限于处理一维数据数组?
我还没有找到使用Span处理testMulti数组的明显方法.

Is the design of Span limited to working with single dimensional arrays of data?
I've not found an obvious way of working with the testMulti array using Span.

推荐答案

您可以创建具有不受管内存的Span.这样一来,您就可以随意切片和切丁.

You can create a Span with unmanaged memory. This will allow you to Slice and Dice indiscriminately.

unsafe
{
    Span<T> something = new Span<T>(pointerToarray, someLength); 
}

完整演示

unsafe public static void Main(string[] args)
{
   double[,] doubles =  {
         { 1, 2, 3, 4 },
         { 5, 6, 7, 8 },
         { 9, 9.5f, 10, 11 },
         { 12, 13, 14.3f, 15 }
      };

   var length = doubles.GetLength(0) * doubles.GetLength(1);

   fixed (double* p = doubles)
   {
      var span = new Span<double>(p, length);
      var slice = span.Slice(6, 5);

      foreach (var item in slice)
         Console.WriteLine(item);
   }
}

输出

7
8
9
9.5
10

其他选择是将其重新分配给一维数组,补偿罚款,然后请勿通过

Other options would be to reallocate to a single dimension array, cop the penalty and do not Pass-Go

  • BlockCopy
  • 或p/直接调用memcpy并使用unsafe和指针
  • Cast<T>例如multiDimensionalArrayData.Cast<byte>().ToArray()
  • BlockCopy
  • or p/invoke memcpy directly and use unsafe and pointers
  • Cast<T> eg multiDimensionalArrayData.Cast<byte>().ToArray()

对于大型数组,前2个将表现更好.

The first 2 will be more performant for large arrays.

这篇关于跨度和二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆