Span and two dimensional Arrays

前端 未结 4 758
轮回少年
轮回少年 2020-12-19 08:16

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

double[,] testMulti = 
    {
        { 1, 2, 3, 4 },
        { 5         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-19 08:47

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

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

    Full Demo

    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(p, length);
          var slice = span.Slice(6, 5);
    
          foreach (var item in slice)
             Console.WriteLine(item);
       }
    }
    

    Output

    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
    • or p/invoke memcpy directly and use unsafe and pointers
    • Cast eg multiDimensionalArrayData.Cast().ToArray()

    The first 2 will be more performant for large arrays.

提交回复
热议问题