I'm creating a performance-critical application that implements image manipulation. I'm using some pixel pointers using my struct named Pixel
to do some processing. I've got lots of code parts that iterate over the whole bitmap data, and for the sake of code reusability and modularity, I'm designing a method that will take an action and apply it to all pixels of the image (like a map function). However, when I write Action<Pixel*>
Visual Studio complains about the code saying the type Pixel*
may not be used as a type argument. The whole class is in an unsafe
context and I'm using Pixel
pointers everywhere, but I just can't use a pixel pointer as an Action's template class.
I can use Action<IntPtr>
but I'll need to convert it to appropriate pointers inside the method body in EVERY iteration, which would kill the whole idea of being "performance critical".
It seems nothing is forcing you to use Action<T>
, so you can create your own delegate type. I didn't figure out a way to do this in a generic way, but this works:
unsafe delegate void PixelAction(Pixel* ptr);
Keep in mind that if this is really performance critical, invoking a delegate is slower than just calling a method directly. Maybe another way could be better, like duplicating code (if that would work in your case), or code generation, either at compile time or at runtime using Reflection.Emit or CodeDOM.
Pointer types are not classes, and so they can't be used as generic type arguments.
I think your only approach would be to define Action<IntPtr>, and cast as necessary on both sides. I don't think the performance hit will be as bad as you think when compiling with optimizations.
EDIT: turns out the below doesn't work (CS0208)
Either that, or instead of using Action<T> defining your own delegate type might work:
delegate void PointerAction<T>(T* ptr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With