I have a byte array which I would like to access by Int32 pointer (unsafe context). I am doing this
byte[] bgImageBytes = new byte[1000];
unsafe
{
fixed (byte* bgImgPtr = bgImageBytes)
{
// I have a byte pointer ... How can I get an Int32 pointer?
}
}
I’m already accessing a pointer returned from kernel32.dll as both Byte and Int32 pointer without any problem. But when I try to make an Int32 pointer on the managed byte array (example above) it seems to complain about it being managed code so it won’t work.
Simply doing UInt32* bgImgIntPtr = (UInt32*)bgImgPtr; results in MDA FatalExecutionEngineError: The CLR has been fatally corrupted. This is most often caused by data corruption, which can be caused by a number of problems, such as calls to malformed platform invoke functions and passing invalid data to the CLR.
My goal: Have both UInt32 and Byte pointers to a single bytearray so I can read the Kinect “heatmap” both as integer and as individual colors. I know I can easily convert between the types, but since I’m working with multiple arrays in different formats it would be much better if I could access them directly without converting between them all the time. There is a lot of plain copying going on so it will just add overhead to keep converting.
Ok, funny story. Turns out it is not only possible to reference an null array, but it also points to somewhere. This really messed up my debugging.
The “UInt32* bgImgIntPtr = (UInt32*)bgImgPtr;” that leads to the MDA exception is because the array was uninitialized. Making a pointer to the bytepointer that goes to the bytearray is the correct way to go.
The answer: