简体   繁体   English

指向Byte []数组的不安全Int32指针

[英]Unsafe Int32 pointer to a Byte[] array

I have a byte array which I would like to access by Int32 pointer (unsafe context). 我有一个字节数组,我想通过Int32指针访问(不安全的上下文)。 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. 我已经将从kernel32.dll返回的指针作为Byte和Int32指针访问,没有任何问题。 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. 但是当我尝试在托管字节数组上创建一个Int32指针时(上面的示例),它似乎抱怨它是托管代码,所以它不起作用。

Simply doing UInt32* bgImgIntPtr = (UInt32*)bgImgPtr; 简单地做UInt32* bgImgIntPtr = (UInt32*)bgImgPtr; results in MDA FatalExecutionEngineError: The CLR has been fatally corrupted. 导致MDA FatalExecutionEngineError: CLR已被致命损坏。 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. 这通常是由数据损坏引起的,数据损坏可能是由许多问题引起的,例如调用格式错误的平台调用函数以及将无效数据传递给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. 我的目标:将UInt32和Byte指针都指向一个bytearray,这样我就可以将Kinect“热图”作为整数和单独颜色读取。 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;" “UInt32 * bgImgIntPtr =(UInt32 *)bgImgPtr;” that leads to the MDA exception is because the array was uninitialized. 导致MDA异常的原因是阵列未初始化。 Making a pointer to the bytepointer that goes to the bytearray is the correct way to go. 制作一个指向bytearray的字节指针的指针是正确的方法。

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;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM