本代码演示了如何创建一个unsafe的指针数组记录struct的地址信息
class UnsafePointerArray
{
public struct AStruct
{
public int anInteger;
}
public static void CreatePointerArray()
{
AStruct struct0 = new AStruct();
AStruct struct1 = new AStruct();
AStruct struct2 = new AStruct();
unsafe
{
AStruct*[] StructPtrs = new AStruct*[3];
// load addresses into pointer array
StructPtrs[0] =
StructPtrs[1] =
StructPtrs[2] =
fixed (AStruct** ptrArrayStructPtrs = StructPtrs)
{
for (int i = 0; i < 3; i++)
{
ptrArrayStructPtrs[i]->anInteger = i * 2;
Console.WriteLine ("&struct" + i + " = "
+ String.Format ("{0:x2}", (int) ptrArrayStructPtrs[i]));
Console.WriteLine ("&struct" + i + ".anInteger = "
+ ptrArrayStructPtrs[i]->anInteger + "\n\n");
}
}
}
}
}
这段代码输出结果如下:
&struct0 = 3afec80 &struct0.anInteger = 0 &struct1 = 3afec7c &struct1.anInteger = 2 &struct2 = 3afec78 &struct2.anInteger = 4
