如何针指向管理对象在C#中? [英] How to pin a pointer to managed object in C#?

查看:95
本文介绍了如何针指向管理对象在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

未管理code调用我的函数。在第一个功能,我应该指针传递回我的管理对象。有时后我的一些其他功能被调用与相同的指针作为参数之一。我应该取消对它的引用,并用它来进行一些计算,然后,如果它是没有必要处置。 为了削减长话短说,我需要针的对象,以便GC不会动它直到我处置。如何做到这一点在C#中?            先谢谢了。

Unmanaged code calls my functions. In first function I should pass back pointer to my managed object. Sometimes later some of my other functions get called with that same pointer as one of parameters . I should dereference it and use it to perform some calculations and then if it is not needed dispose of it. To cut the story short I need to pin that object so that GC won't move it til I dispose of it. How to do that in C# ? Thanks in advance.

推荐答案

要针在C#中的对象,你可以使用GCHandle.Alloc方法与第二个参数GCHandleType.Pinned。对象保持固定,直到的GCHandle实例使用GCHandle.Free方法释放。

To pin an object in C#, you can use GCHandle.Alloc Method with second parameter GCHandleType.Pinned. Object remains pinned until GCHandle instance is released using GCHandle.Free Method.

这篇关于如何针指向管理对象在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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