Access violation exception when use method Marshal.PtrToStructure in a loop

落爺英雄遲暮 提交于 2019-12-22 12:40:42

问题


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


来源:https://stackoverflow.com/questions/16931369/access-violation-exception-when-use-method-marshal-ptrtostructure-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!