0

我有一个问题,但我不明白,我不知道问题的根本原因。我有一个小程序,当在 win 7(64 位)上运行它时发生访问冲突异常。在 winXP(32 位)上不会发生此异常。之后,我更改了一些代码并且不会发生访问冲突异常(在 win 7 和 winxp 上)。我不是异常的根本原因。代码如下。之前的代码(在win 7上发生访问冲突异常)。

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

修改后的代码(不发生访问冲突异常):

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

请帮助我在代码之前找到访问冲突异常的根本原因。

4

1 回答 1

0

我认为您的问题可能出在这一行:

currentVertex = (IntPtr)((int)currentVertex.ToInt64() + Marshal.SizeOf(oVertext));

在 64 位操作系统上,将 64 位值转换为 32 位 int 时可能会发生溢出。

要确定是否是这种情况,请将其放在checked周围并进行测试以查看它是否引发溢出异常:

checked
{
    currentVertex = (IntPtr)((int)currentVertex.ToInt64() + Marshal.SizeOf(oVertext));
}
于 2013-06-06T08:24:08.033 回答