简体   繁体   中英

Reshape c# array in place

There are may operations on arrays that do not depend on the rank of an array. Iterators are also not always a suitable solution. Given the array

double[,] myarray = new double[10,5];

it would be desirable to realize the following workflow:

  1. Reshape an array of Rank>1 to a linear array with rank=1 with the same number of elements. This should happen in place to be runtime efficient. Copying is not allowed.
  2. Pass reshaped array to a method defined for Rank=1 arrays only. eg Array.copy()
  3. Reshape result array to original rank and dimensions.

There is a similar question on this topic: How to reshape array in c# . The solutions there use memory copy operation with BlockCopy().

My question are: Can this kind of reshaping be realized without memory copy? Or even in a temporary way like creating a new view on the data?

There wording to this is a little tough, yet surely pointers unsafe and fixed would work. No memory copy, direct access, add pepper and salt to taste

The CLR just wont let you cast an array like you want, any other method you can think of will require allocating a new array and copy (which mind you can be lightening fast). The only other possibly way to so this is to use fixed, which will give you contiguous 1 dimensional array.

unsafe public static void SomeMethod(int* p, int size)
{
   for (var i = 0; i < 4; i++)
   {
      //Perform any linear operation
      *(p + i) *= 10;
   }
}
...

var someArray = new int[2,2];
someArray[0, 0] = 1;
someArray[0,1] = 2;
someArray[1, 0] = 3;
someArray[1, 1] = 4;

//Reshape an array to a linear array 
fixed (int* p = someArray)
{
     SomeMethod(p, 4);
}

//Reshape result array to original rank and dimensions.

for (int i = 0; i < 2; i++)
{
   for (int j = 0; j < 2; j++)
   {
      Console.WriteLine(someArray[i, j]);
   }
}

Output

10
20
30
40

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM