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,所以額外的位會丟失。 –
很了不起,我明白了。 –