Water in Wine with C#

A common need when working with images is to convert arrays containing pixels from a type to another.

For example an uint[] to byte[] conversion is common, but very slow and memory intensive.

Here the fastest method I developed for real-time applications:


The code is unsafe (additional testing recommended) and may not work with future CLR Runtimes, but it's pretty readable and fast.

In few words the code is changing the type of the array by overwriting the CLR Method Table and then resizing the array in a similiar way. A new array (of the desired type) pointing to the original one is then returned. The original data is never copied and this makes this method very fast to execute.

Here how to use the function CastArray:


An array containing a 4K 32 bit image can be casted with a great speedup compared to an Array copy with standard solutions such as Buffer.BlockCopy.

The drawback is that now we have overwritten the original array size and if we use the original array, we should manually ensure that we are not reading over it's end.

The byte[] is actually a reference array and changing it will change the uint[] (and the opposite), but this can avoid further casts.

Note: As I already done in the electro-logic blog, new posts starting from this one are only in English to enable more people to read them, but you can still contact me or leave a comment in Italian if you prefer.

That's all for today

Print | posted on venerdì 24 novembre 2023 22:51

Comments on this post

# re: Water in Wine with C#

Requesting Gravatar...
Nice technique! I tried it and is very fast
Left by Brian on nov 25, 2023 11:59

# re: Water in Wine with C#

Requesting Gravatar...
Ottimo trucchetto
Left by Alessandro on nov 27, 2023 9:10

Your comment:

 (will show your gravatar)
 
Please add 7 and 2 and type the answer here: