如何固定由C#中的Marshal.AllocHGlobal()分配的内存? [英] How to pin memory allocated by Marshal.AllocHGlobal() in C#?

查看:220
本文介绍了如何固定由C#中的Marshal.AllocHGlobal()分配的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何固定由Marshal.AllocHGlobal()分配的内存?

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

我的第一次尝试是:

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

尽管我认为这只会固定 IntPtr ,而不是 IntPtr 所引用的内存块.

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

推荐答案

AllocHGlobal 分配的内存已固定.返回的 IntPtr 是固定位置的地址.

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

更新:要学究,您实际上不能固定"由 AllocHGlobal 分配的内存,固定某些东西意味着告诉垃圾回收器不要在内存中移动对象.由 AllocHGlobal 分配的内存是非托管内存",这意味着它不是由垃圾收集器管理的内存.

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.

这篇关于如何固定由C#中的Marshal.AllocHGlobal()分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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