我使用以下方法保留了一个无人数组:
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(array[0]) * array.Length);然后释放它:
Marshal.FreeHGlobal(ptr );据我所知,这将正确释放内存,不会发生内存泄漏。 我的问题:这是真的吗? 如果是的话,那是怎么回事? 关于每个保留数据,是Marshal state-full和store元数据?
I have reserved an unmanned array using:
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(array[0]) * array.Length);then free it using:
Marshal.FreeHGlobal(ptr );as far as I read, this will free the memory correctly and no memory leak gonna happen. My question: is this true? if it is, how that works? is the Marshal state-full and store meta-data about every reserved data?
最满意答案
AllocHGlobal方法公开LocalAlloc函数。 FreeHGlobal方法公开了LocalFree函数。 内存管理不是由任何托管组件完成的。 它由这些windows api函数背后的代码完成。
回答你的问题:是的,它必须跟踪分配的大小。 您可以通过调用LocalSize函数来检索句柄的大小。 说实话,我不知道它是如何在内部完成的,但你不需要知道。
The AllocHGlobal method exposes the LocalAlloc function. And the FreeHGlobal Method exposes the LocalFree function. The memory management is not being done by any managed component. It is done by the code behind these windows api functions.
To answer your question: Yes it has to keep track of the allocated size. You can retrieve the size of a handle by calling LocalSize function. To be honest, I don't know how its being done internally, but you don't need to know that.
更多推荐
发布评论