How to pin memory allocated by Marshal.AllocHGlobal() in C#?

 ̄綄美尐妖づ 提交于 2021-02-05 11:22:10

问题


How do you pin memory allocated by Marshal.AllocHGlobal()?

My first attempt was the following:

int bytes = 10;
IntPtr ip = Marshal.AllocHGlobal(bytes);
GCHandle iph = GCHandle.Alloc(ip, GCHandleType.Pinned);

Although I think this only pins the IntPtr and not the block of memory referred to by the IntPtr.


回答1:


The memory allocated by AllocHGlobal is already pinned. the IntPtr that is returned is the address of the pinned location.

UPDATE: To be pedantic you can't actually "pin" the memory allocated by AllocHGlobal, to pin something means to tell the Garbage Collector to not move the object in memory. The memory allocated by AllocHGlobal is "unmanaged memory" which means it is memory that is not managed by the Garbage Collector.

No process besides the Garbage Collector moves memory around in your program, and the Garbage Collector does not care about unmanaged resources.



来源:https://stackoverflow.com/questions/40539292/how-to-pin-memory-allocated-by-marshal-allochglobal-in-c

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