本文介绍了在循环中使用方法Marshal.PtrToStructure时访问冲突异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序(C#)中,我使用了方法Marshal.PtrToStructure来转换对象,并在循环中添加了一个内存地址以结构化.在第一个元素上,此工作正常.但是在第二个元素上,会发生访问冲突异常.

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.

访问冲突异常仅发生在win 7(64位)上,不会发生在win xp(32位)上.

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.

请帮助我.

注意:我使用.NET Framework 3.5.

Note: I use .NET Framework 3.5.

代码如下:

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

谢谢.

推荐答案

当我更改某些代码时,不会发生访问冲突.但是,我不了解此问题的根本原因.发生什么访问冲突异常?

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?

代码修改如下:

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

这篇关于在循环中使用方法Marshal.PtrToStructure时访问冲突异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 07:24