我得到了以下 MemoryAddressExtensions 代码,它显示了 C# 中的对象地址
想知道什么是
IntPtr**
and
**(IntPtr**)
Thanks
public static class MemoryAddressExtenstion
{
public static string Address(this object me)
{
unsafe
{
TypedReference tr = __makeref(me);
var ptr = **(IntPtr**)&tr;
return "0x" + ptr.ToString("X");
}
}
}
变量地址 https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/how-to-obtain-the-address-of-a-variable
__makeref http://benbowen.blog/post/fun_with_makeref/
类型化参考 https://msdn.microsoft.com/library/system.typedreference(v=vs.110).aspx
源代码 https://github.com/supershowwei/stringpool.lab
遗憾的是我无法以更好的方式解释它们......所以如果有人可以纠正我那么谢谢!
在 .NET 中称为“引用”,在 C 中称为“指针”。那么什么叫做object me
在 C# 中,将是void *me
,一个指针(称为me
) 到一个对象。
TypedReference tr = __makeref(me);
这创建了一个TypedReference
到变量me
。正如我所说,引用与 C 指针非常相似(事实上,如果你看一下是源代码 https://referencesource.microsoft.com/#mscorlib/system/typedreference.cs,fa749891bb84425e你会看到它包含一个IntPtr Value
)。所以在 C 中它会是:
void **tr = &me;
(在 .NET 中,指向TypedReference
,在 C 中是指向指针的指针)
现在代码正在创建第三级间接性
void ***temp = &tr;
然后它取消引用它两次
void *ptr = **temp;
所以我们有一个*ptr
与最初的相同*me
。我们这样做是因为通常在 C# 中您无法直接将引用转换为等效指针。
他们为什么要这样做?因为您通常无法将引用强制转换为指针(您不能(IntPtr)me
),你也不能直接获取引用地址(所以你不能&me
)。但你可以创建一个TypedRefence
这相当于做&me
。现在,遗憾的是你做不到(IntPtr*)tr
, or (IntPtr)tr
。但幸运的是你可以&tr
。现在您终于能够获得一个真正的指针,并且您可以开始取消引用它以返回到您想要的初始指针。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)