Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        去年关闭。
                                                                                            
                
        
我正在使用Kinect v2,其中包含以下CameraSpacePoint结构:

public struct CameraSpacePoint : IEquatable<CameraSpacePoint>
{
    public float X;
    public float Y;
    public float Z;
}


CameraSpacePoint还包含一些方法EqualsGetHashCode等,上面没有显示,以保持帖子的简洁和简短。

好吧,我在类构造函数中定义cameraSpacePoints,如下所示:

IntPtr cameraSpacePoints = Marshal.AllocHGlobal(512 * 424 * 4 * 3);


下面是上述内存分配的说明:


512:宽度
424:身高
4:单个“浮点数”所需的字节
3:总共三个变量,即“ X”,“ Y”和“ Z”


稍后,我使用CoordinateMapper将值复制到cameraSpacePoints,如下所示:

coordinateMapper.MapDepthFrameToCameraSpaceUsingIntPtr(depthFrameData,
                                                   512 * 424 * 2,
                                                   cameraSpacePoints,
                                                   512 * 424 * 4 * 3);


看起来很完美。现在,我想从cameraSpacePoints获取值。所以我在unsafe块中使用了以下代码:

float* cameraSpacePoint = (float*)cameraSpacePoints;
for (var index = 0; index < 512 * 424; index++)
{
    float X = cameraSpacePoint[index];
    float Y = cameraSpacePoint[index + 1];
    float Z = cameraSpacePoint[index + 2];
}


我在可视化时意识到这似乎没有用。在我看来,使用IntPtr从cameraSapacePoints访问元素时会有些混乱。这里缺少什么?有什么建议吗?

最佳答案

在您的初始代码中,您将IntPtr(指向CameraSpacePoint的array [])强制转换为原始浮点指针。如果您将IntPtr解释为原始float,由于您一次要处理3个点(x,y和z),则每次循环都需要增加3个浮点数,例如(为了清楚起见,我将变量重命名):

var floats = (float*)cameraSpacePoints;
for (var index = 0; index < 512 * 424; index+=3)
{
    var x = floats[index];
    var y = floats[index + 1];
    var z = floats[index + 2];
    var myCameraSpacePoint = new CameraSpacePoint
    {
       X = x,
       Y = y,
       Z = z
    };
   // use myCameraSpacePoint here
}


但这是处理数据的一种极其低效的方式,因为无论如何该数据最初都是CameraSpacePoint。更好的方法是将结构直接转换回实际类型:

var cameraSpacePoints = (CameraSpacePoint*)cameraSpacePoints;
for (var index = 0; index < 512 * 424; index++)
{
    var cameraSpacePoint = cameraSpacePoints[index];
    // Do something with cameraSpacePoint
}


通过强制转换为正确的类型(CameraSpacePoint),我们还提高了代码的健壮性-例如如果将来在新版本的CameraSpacePoint中添加了其他字段,则可以再次针对新版本重新编译代码,而直接访问float会破坏封装并增加维护难度。

之所以不再需要将循环增加3,是因为当我们在cameraSpacePoints[index]上使用下标/索引操作时,是因为编译器知道在元素的位置之后的偏移量n * sizeof(CameraSpacePoint)处找到元素n。初始cameraSpacePoints[0]sizeof(CameraSpacePoint)是3个浮点数的大小。

10-08 13:36