kasperhj
kasperhj

Reputation: 10482

How can I make a pointer generic in C#?

I have a WriteableBitmap which I use an unsafe method to plot pixels. The essential part looks like this:

private unsafe void DrawBitmap(WriteableBitmap bitmap, byte[] pixels)
{
         // Boilerplate omitted... 

        fixed (byte* pPixels = pixels)
        {
            for (int y = 0; y < height; y++)
            {
                var row = pPixels + (y * width);
                for (int x = 0; x < width; x++)
                {
                    *(row + x) = color[y + height * x];
                }
            }
        }

        bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width*pf.BitsPerPixel/8, 0);
}

However, it is not certain that what the user wants to plot is of the type byte, and it would make sense to make this method generic (i.e. DrawBitmap<T>) but how can I make the pointer pPixels of type T*?

Is there some other trick that will make my DrawBitmap generic?

Upvotes: 5

Views: 149

Answers (1)

LukeHennerley
LukeHennerley

Reputation: 6444

Consider using overloads.

public void MethodA(byte[] pPixels) {}
public void MethodA(int[] pPixels {}
//etc...

Upvotes: 3

Related Questions