Access violation exception when use method Marshal

2019-05-20 18:29发布

问题:

In my program (C#), i used method Marshal.PtrToStructure to convert object add a memory address to structure in a loop. At the first element, this work normal. But at the second element, the access violation exception occurs.

The access violation exception only occurs on win 7 (64 bits), it does not occur on win xp (32 bits).

I don't know cause and solution for it.

Please help me.

Note: I use .NET Framework 3.5.

Code as bellow:

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

Thanks.

回答1:

When i change some code, access violation does not occur. However, i don't understand root cause of this problem. What access violation exception occur?

Code modify as bellow:

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