对象没有固定的地址,因为它们可以通过GC移动。如果您想获得该地址,您需要告诉GC将其与fixed statement固定在一起。请看看Understanding Memory References, Pinned Objects, and Pointers
您将需要使用编译“不安全”模式(VS项目 - >属性 - >生成并勾选“允许不安全的代码”)
using System;
internal class Program
{
private static unsafe void Main(string[] args)
{
Point point = new Point { X = 10, Y = 20};
long a = 1;
long* pA = &a;
Console.WriteLine("'a' pointer value: \t{0}", *pA);
Console.WriteLine("'a' pointer address: \t{0:x16}", (long)pA);
Console.WriteLine("'point' value: \t\t{0:x16}", *(pA - 1));
// the location of 'point' on the stack
long prP = (long)(pA - 1);
long* pP = *(long**)prP;
Console.WriteLine("'point' address: \t{0:x16}", *pP);
Console.WriteLine("'point.Y' value: \t{0}", *(pP + 1));
Console.WriteLine("'point.X' value: \t{0}", *(pP + 2));
Console.ReadLine();
}
}
internal class Point
{
public int X;
public long Y;
}
输出:
'a' pointer value: 1
'a' pointer address: 000000001cb6dfa8
'point' value: 00000000027dd788
'point' address: 000007fe8a0851a8
'point.Y' value: 20
'point.X' value: 10
可能是某些“不安全”的东西,但通常你不需要。 – crashmstr
“get”是什么意思?你在寻找一些什么? –
您可以使用'unsafe'获得某些(原始)类型的指针,但它不适用于复杂类型。此外,.NET实例的物理内存位置不能保证随着时间的推移而被修复 - 对象可能会移动。即使你获得了一个物体的物理位置,只要它是固定的(“固定”),它就是有效的。 – xxbbcc