5

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?

kasperhj
  • 10,052
  • 21
  • 63
  • 106
  • 4
    "Generic" means that the same method (same IL) works for *all* types, not just the ones you're actually using as type parameter. Different integer types (byte, int, ...) require different IL, so you can't make the method generic. – dtb Feb 19 '13 at 08:58
  • I don't quite see where `pPixels` or `pixels` is coming from? Post all of the code? – LukeHennerley Feb 19 '13 at 08:58
  • 1
    But as @dtb says, you need a type which in simple terms derives from `object`, value types can not be used in generic methods. I would consider using different overloads of the method instead. – LukeHennerley Feb 19 '13 at 09:00
  • @LukeHennerley It's `color`. I've corrected it. – kasperhj Feb 19 '13 at 09:04
  • 1
    @LukeHennerley: That's complete non-sense. (1) value types derive from object and (2) you can use them in a generic class. – Daniel Hilgarth Feb 19 '13 at 09:09
  • @DanielHilgarth Sorry, it's early in the morning :( – LukeHennerley Feb 19 '13 at 09:11
  • 1
    possible duplicate of [C#: Using a generic to create a pointer array](http://stackoverflow.com/questions/1631754/c-using-a-generic-to-create-a-pointer-array) – sloth Feb 19 '13 at 09:17

1 Answers1

3

Consider using overloads.

public void MethodA(byte[] pPixels) {}
public void MethodA(int[] pPixels {}
//etc...
LukeHennerley
  • 6,344
  • 1
  • 32
  • 50