A simple example on C++ reinterpret_cast
Today I want to give you a simple example on using reinterpret_cast. First than all lets check the documentation at cppreference.com.
As it says "It is purely a compiler directive which instructs the compiler to treat the sequence of bits (object representation) of expression as if it had the type new_type.". So basically if you have a sequence or an array of some type of data you can reinterpret this array as another type of data, but be careful, not as any other type of data. Better go with the simple example.
In CUDA you have a struct called uchar4 wich basically can be represented as:
I use this structure to load images as an Aos (Array of structures).
At some point of my program I needed to pass this array to a function with the following signature:
This function receives the raw data of pixels in the format RGBARGBARGBA... So as we have read this is a task for reinterpret_cast. This because we know uchar4 in the background is just an struct holding in sequence the values for RGBA. So we have:
Then we can call the update function as:
Syntaxis
reinterpret_cast < new_type > ( expression )
In CUDA you have a struct called uchar4 wich basically can be represented as:
struct uchar4 { unsigned char x; unsigned char y; unsigned char z; unsigned char w; };
I use this structure to load images as an Aos (Array of structures).
Uint64 PixelsBufferSize = ImageWidht * ImageHeight * sizeof(uchar4); uchar4* Pixels = new uchar4[PixelsBufferSize]; memcpy(Pixels, SourceImage.getPixelsPtr(), PixelsBufferSize);
At some point of my program I needed to pass this array to a function with the following signature:
void update(const unsigned char* pixels);
This function receives the raw data of pixels in the format RGBARGBARGBA... So as we have read this is a task for reinterpret_cast. This because we know uchar4 in the background is just an struct holding in sequence the values for RGBA. So we have:
uchar4 uchar4 uchar4 ... = unsigned char unsigned char unsigned char ...
Then we can call the update function as:
DynamicTexture.update(reinterpret_cast < Uint8* > (Pixels));
Comments
Post a Comment