Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();

Whilst testArray and testString have a AsSpan extension, no such extension exists for 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
463 views
Welcome To Ask or Share your Answers For Others

1 Answer

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); 
}

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<double>(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<T> eg multiDimensionalArrayData.Cast<byte>().ToArray()

The first 2 will be more performant for large arrays.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...