在C#中的对象的内存地址 [英] Memory address of an object in C#
问题描述
我已经写了前一段时间(对于.NET 3.5)的函数,而现在我已经升级到4.0 我无法得到它的工作。
I have a function written some time ago (for .NET 3.5), and now that I have upgraded to 4.0 I can't get it to work.
的功能是:
public static class MemoryAddress
{
public static string Get(object a)
{
GCHandle handle = GCHandle.Alloc(a, GCHandleType.Pinned);
IntPtr pointer = GCHandle.ToIntPtr(handle);
handle.Free();
return "0x" + pointer.ToString("X");
}
}
现在,当我把它称为 - MemoryAddress.Get(新车(蓝))
Now, when I call it - MemoryAddress.Get(new Car("blue"))
public class Car
{
public string Color;
public Car(string color)
{
Color = color;
}
}
我得到的错误:对象包含非基本或非blittable数据
I get the error: "Object contains non-primitive or non-blittable data."
它为什么不能工作了? 我怎么能现在得到管理对象的内存地址?
Why doesn't it work anymore? How can I now get the memory address of managed objects?
推荐答案
您可以使用GCHandleType.Weak,而不是寄托。另一方面,有另一种方法来获得指向对象的指针:
You can use GCHandleType.Weak instead of Pinned. On the other hand, there is another way to get pointer to an object:
object o = new object();
TypedReference tr = __makeref(o);
IntPtr ptr = **(IntPtr**)(&tr);
需要不安全块,是非常,非常危险的,不应该在所有使用的。 ☺
Requires unsafe block and is very, very dangerous and should not be used at all. ☺
这篇关于在C#中的对象的内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!