问题描述
在我的程序 (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 时的访问冲突异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!