Unsafe Int32 pointer to Byte [] array

I have an array of bytes that I would like to get using the Int32 pointer (insecure context). I'm doing it

byte[] bgImageBytes = new byte[1000]; unsafe { fixed (byte* bgImgPtr = bgImageBytes) { // I have a byte pointer ... How can I get an Int32 pointer? } } 

I am already accessing the pointer returned from kernel32.dll, both the Byte and Int32 pointer without any problems. But when I try to make an Int32 pointer on a managed byte array (example above), it seems to complain that it is controlled by code, so it won't work.

Just doing UInt32* bgImgIntPtr = (UInt32*)bgImgPtr; leading to MDA FatalExecutionEngineError: CLR was fatally damaged. This is most often caused by data corruption, which can be caused by a number of problems, such as calls to the incorrect platform function to call and transfer invalid data to the CLR.

My goal: Point both UInt32 and Byte pointers to a single bytearray so that I can read the Kinect heat map, both whole and individual colors. I know that I can easily convert between types, but since I work with several arrays in different formats, it would be much better if I could access them directly without having to switch between them all the time. There is a lot of simple copying, so it just adds the overhead to convert.

+4
source share
1 answer

Good, funny story. It turns out that you cannot only reference a null array, but it also points to something. It really messed up my debugging.

"UInt32 * bgImgIntPtr = (UInt32 *) bgImgPtr;" which results in an MDA exception because the array is not initialized. The right way is to make a pointer to a bytepointer going to bytearray.

Answer:

 byte[] bgImageBytes = new byte[1000]; unsafe { // Make a byte pointer to the byte array fixed (byte* bgImgPtr = bgImageBytes) { // Make a UInt32 pointer to the byte pointer UInt32* bgImgIntPtr = (UInt32*)bgImgPtr; } } 
+6
source

Source: https://habr.com/ru/post/1337662/


All Articles