0
我有一个问题,但我不明白,我不知道问题的根本原因。 我讨厌一个小程序,并在win 7(64位)上运行它时发生访问冲突异常。 winXP(32位)不会发生此异常。 之后,我改变了一些代码和访问冲突异常不会发生(在胜利7和winxp上)。 我不会引发异常。 代码如下。 之前的代码(获胜7时发生访问冲突异常)。询问C指针和访问内存#
[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);
}
}
请帮我在代码前发现访问冲突异常的根本原因。
感谢您的帮助。 当64位数值转换为32位int时,你能告诉我有关溢出的详细信息吗? –
好吧,如果64位数值的值大于int.MaxValue或小于int.MinValue,不适合32位int,所以额外的位会丢失。 –
很了不起,我明白了。 –