4

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.

4
  • Is bgImageBytes actually new byte[1000]? or is it being passed to unmanaged code? Commented Jan 30, 2011 at 13:16
  • Just tested: byte[] a = new byte[100]; fixed (byte* b = a) { Int32* c = (Int32*)b; c[0] = 1000; } works for me on .NET 4. Also works for UInt32. What version are you using? Is it the actual code? Commented Jan 30, 2011 at 13:18
  • It is purely managed and initialized to the size of the image based on some calculations (so 1000 is actually more like stride+heightwidthcolordepth, but thats irrelevant). Commented Jan 30, 2011 at 13:19
  • Maybe you should post a little more code, it's difficult to see what's actually going on Commented Jan 30, 2011 at 13:21

1 Answer 1

6

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:

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;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.