views:

1365

answers:

4

Is there an efficient way to take a subset of a C# array and pass it to another peice of code (without modifying the original array)? I use CUDA.net which has a function which copies an array to the GPU. I would like to e.g. pass the function a 10th of the array and thus copy each 10th of the array to the GPU seperately (for pipelining purposes).

Copying the array in this way should be as efficient as copying it in one go. It can be done with unsafe code and just referencing the proper memory location but other than that I'm not sure. The CopyTo function copies the entire array to another array so this does not appear useful.

A: 

I'm not sure how efficient this is but...

int[] myInts = new int[100];

//Code to populate original arrray

for (int i = 0; i < myInts.Length; i += 10)
{
    int[] newarray = myInts.Skip(i).Take(10).ToArray();
    //Do stuff with new array
}
Eoin Campbell
A: 

You could use extension methods and yield return:

public static IEnumerable Part<T>(this T[] array, int startIndex, int endIndex )
{
    for ( var currentIndex = startIndex; currentIndex < endIndex; ++currentIndex )
        yield return array[currentIndex];
}
David Kemp
+1  A: 

Okay, I'd misunderstood the question before.

What you want is System.Buffer.BlockCopy or System.Array.Copy.

The LINQ ways will be hideously inefficient. If you're able to reuse the buffer you're copying into, that will also help the efficiency, avoiding creating a new array each time - just copy over the top. Unless you can divide your "big" array up equally though, you'll need a new one for the last case.

Jon Skeet
+1  A: 

You could try Marshal.Copy if you need to go from an array of bytes to an unmanaged pointer. That avoids creating unsafe code yourself.

Edit: This would clearly only work if you reimplement their API. Sorry - misunderstood. You want an efficient subarray method.

It strikes me that what you really want is an api in the original class of the form

void CopyToGpu(byte[] source, int start, int length);
plinth