Henrik123 Henrik123 - 1 month ago 11
C# Question

C# reshape array 1->2 D without duplicating data

I'm using a C# SDK from a camera manufacturer. They have a method:

CaptureImage(struct ExpSettings, ref ushort[] pixelbuffer)


I wish to reshape the one dimensional array pixelbuffer to a 2D array.
Right now I'm using
Buffer.BlockCopy
as suggested by Jon Skeet in a similiar question here on SO.

However I was thinking if there is a way (in C#) of doing this without having to copy the actual data. In C I guess that you could for example use a union.

Can you somehow create an array
UInt16[,] My2DImageData = new UInt[1000, 1000]
and then "point the data array" to the pixelbuffer above?

Thank you for your time.
Kind regards / Henrik

Answer

If you only interesting in accessing member via indexer and don't want to duplicate data, you can use wrapper class.

class ArrayWrapper<T>
{
    private readonly T[] _arr;
    private readonly int _w, _h;
    public ArrayWrapper(T[] arr, int w, int h)
    {
        if(arr == null)
            throw new ArgumentNullException("arr");

        if(arr.Length != w*h)
            throw new ArgumentException("Invalid array length", "arr");

        _arr = arr;
        _w = w;
        _h = h;
    }

    public T this[int i, int j]
    {
        get { return _arr[i*_w + j]; }
    }
}

var arr = new[] {
    0,  1,  2,  3, 
    4,  5,  6,  7, 
    8,  9,  10, 11, 
    12, 13, 14, 15 };
var wrapper = new ArrayWrapper<int>(arr, 4, 4);
Console.WriteLine(wrapper[1, 1]); // prints 5
Comments