的GCHandle来获取.NET对象的地址(指针) [英] GCHandle to get address(pointer) of .net object

查看:570
本文介绍了的GCHandle来获取.NET对象的地址(指针)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法

GCHandle objHandle = GCHandle.Alloc(obj,GCHandleType.WeakTrackResurrection);
int address = GCHandle.ToIntPtr(objHandle).ToInt32();  

和我能回想起

Object obj = GCHandle.FromIntPtr(IntPtr(address)).Target;

好了,目的是为了保存地址在原生类,并有其本身的对象是相关型号到.NET对象的信息。
AFAIK地址不会因为allocing的改变,这是真的还是没有人有更好的想法为我的目的是什么?

Well, the purpose is to store the address in a native class and have an information of which native object is releated to which .net object.
AFAIK the address does not change because of allocing, is it true or does anyone have a better idea to serve my purpose?

感谢

推荐答案

随着Tim和thecoop指出,GCHandle.Alloc可能prevent垃圾收集,但实际的对象地址可以改变,因为除非你脚GC可移动物体周围的对象。此外,你的code使用 GCHandleType.WeakTrackResurrection 这将不是事件prevent垃圾收集。 GCHandle.ToIntPtr 会给手柄,可以圆绊倒非托管呼叫的地址。实际的目标地址将 AddrOfPinnedObject 的方法进行说明。

As Tim and thecoop has pointed out, GCHandle.Alloc may prevent garbage collection but actual object address can change as GC may move object around unless you pin the object. Further, your code is using GCHandleType.WeakTrackResurrection and that would not event prevent the garbage collection. GCHandle.ToIntPtr will give address of handle that can be round-tripped over unmanaged call. Actual object address will be given by AddrOfPinnedObject method.

说了这么多,国际海事组织,你的code可以起到与非托管对象相关联的.NET对象的目的。这是因为GCHandle.To/FromIntPtr会尽快纠正的GCHandle,你可以通过它达到你的.NET对象(只要它不是垃圾回收)。海事组织,它应该是不重要的,如果实际的对象地址发生了变化与否。

Said all that, IMO, your code may serve the purpose of associating .NET object with unmanaged object. This is because GCHandle.To/FromIntPtr will get back you correct GCHandle and you can reach your .NET object via it (provided its not garbage collected). IMO, it should be immaterial if actual object address had changed or not.

这篇关于的GCHandle来获取.NET对象的地址(指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆