0

When working with stackalloc memory I would like to copy its content to/from an array. I am looking for something similar to Buffer.BlockCopy which would allow me to pass offset in source data and offset in destination.

Is there is such method for stackalloc memory? Or in general -- how to copy memory in one go, without iterating element by element?

int i = 0;
double* window = stackalloc double[max_window_size];
for (int x = 0; x < width; ++x)
{
    window[i] = array[x, y];
    ++i;
}

Important catch: the array I am asking about already exists. So I cannot create an array from stackalloc memory and then copy this array to existing array, because it would invalidate whole point of using stackalloc in the first place.

astrowalker
  • 3,123
  • 3
  • 21
  • 40
  • You might want to look into using Span https://blogs.msdn.microsoft.com/mazhou/2018/03/25/c-7-series-part-10-spant-and-universal-memory-management/ – Mick Oct 10 '18 at 06:43
  • 4
    Please show us a `stackalloc` [mcve] that does copy by iterating one at a time and we'll show you how to do it better. – Enigmativity Oct 10 '18 at 06:43
  • @Enigmativity, here I copy from 2d array a row to a "window" allocated on stack. I would like to copy the content in one take to and from `stackalloc` memory. – astrowalker Oct 10 '18 at 06:52
  • @astrowalker it's still not a complete example... you've not defined array or y – Mick Oct 10 '18 at 07:22
  • @Mick, it is pretty simple, either there is analogy to `Buffer.BlockCopy` or not. If not, any further action is futile, if the former you simply are playing games, and I don't have time for this. I wish you happy day nevertheless. – astrowalker Oct 10 '18 at 07:31
  • @astrowalker - It's still not complete. Can you provide an example that I can copy, paste, and run in a Console App? – Enigmativity Oct 10 '18 at 07:57
  • 1
    @astrowalker I've created a new question to discuss using Span to slice without copying of memory https://stackoverflow.com/questions/52750582/span-and-two-dimensional-arrays/52750659#52750659 – Mick Oct 11 '18 at 01:27

1 Answers1

0

I found the answer in Copy data from from IntPtr to IntPtr

So to answer my own question one has to pin for a second the array (using fixed keyword) and this way one have two pointers at hand. Buffer.MemoryCopy does not have overload with offsets but will little pointer arithmetic you get desired effect.

astrowalker
  • 3,123
  • 3
  • 21
  • 40