在循环中使用方法Marshal.PtrToStructure时访问冲突exception

在我的程序(C#)中,我使用方法Marshal.PtrToStructure转换对象在循环中添加内存地址到结构。 在第一个元素,这项工作是正常的。 但是在第二个元素处,发生访问冲突exception。

访问冲突exception仅在win 7(64位)上发生,在win xp(32位)上不会发生。

我不知道原因和解决方案。

请帮我。

注意:我使用.NET Framework 3.5。

代码如下:

[StructLayout(LayoutKind.Sequential)] public struct gpc_vertex { public float x; public float y; }; private ArrayList DoPolygonOperation() { IntPtr currentVertex = vertexList.vertexes; gpc_vertex oVertext = new gpc_vertex(); for (int j = 0; j < vertexList.num_vertices; j++) { PositionF pos = new PositionF(); oVertext = (gpc_vertex)Marshal.PtrToStructure(currentVertex, typeof(gpc_vertex)); //Access violation exception pos.X = oVertext.x; pos.Y = oVertext.y; Marshal.DestroyStructure(currentVertex, typeof(gpc_vertex)); currentVertex = (IntPtr)((int)currentVertex.ToInt64() + Marshal.SizeOf(oVertext)); posList.Add(pos); } } 

谢谢。

当我更改某些代码时,不会发生访问冲突。 但是,我不明白这个问题的根本原因。 发生什么访问冲突exception?

代码修改如下:

 private ArrayList DoPolygonOperation() { IntPtr currentVertex = vertexList.vertexes; gpc_vertex oVertext = new gpc_vertex(); int currentOffset = 0; for (int j = 0; j < vertexList.num_vertices; j++) { PositionF pos = new PositionF(); oVertext = (gpc_vertex)Marshal.PtrToStructure((IntPtr)(currentVertex.ToInt64() + currentOffset), typeof(gpc_vertex)); pos.X = oVertext.x; pos.Y = oVertext.y; Marshal.DestroyStructure(currentVertex, typeof(gpc_vertex)); currentOffset += Marshal.SizeOf(oVertext); posList.Add(pos); } }