How to pin a pointer to managed object in C#?

北慕城南 提交于 2019-12-04 18:52:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6889614/how-to-pin-a-pointer-to-managed-object-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!