malloc 和 Marshal.AllocHGlobal 之间有什么区别?
我用 C# 编写了一个模块,导出一些要在 C 中使用的函数。 我需要为一些要在 C <-> 之间传递的结构分配一些内存。 C#。
我在 CI 中使用 malloc 分配,在 C# 中使用 Marshal.AllocHGlobal() 分配(分配要传递给 C 的非托管内存)。
如果我 free() 使用 Marshal.AllocHGlobal 分配的内存,以及使用 Marshal.FreeHGlobal() 释放使用 malloc 分配的内存,是否会出现任何问题?
谢谢
I write a module in C# that exports some functions to be used in C.
I need to allocate some memory for some structs to be passed between C <-> C#.
What I allocate in C I do with malloc, and in C# I do with Marshal.AllocHGlobal() (to allocate unmanaged memory to be passed to C).
Is there any problem if I free() the memory allocated with Marshal.AllocHGlobal, and if I release memory with Marshal.FreeHGlobal() which was allocated with malloc?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
黄金法则是您必须从用于分配内存的同一堆中取消分配。
如果使用
malloc()
分配它,则必须使用同一 C RTL 中的free()
取消分配它。同样在托管方面,AllocHGlobal ()
应与FreeHGlobal()
。现在,
AllocHGlobal()
是通过调用Win32函数来实现的LocalAlloc
。因此,您可以通过调用LocalFree
< 来释放此类内存/a> 在本机端。反之亦然。如果要使用本机堆和托管堆之间共享的堆,则更常见的是使用 COM 堆。在本机端使用
CoTaskMemAlloc()
和CoTaskMemFree()
。在托管端使用Marshal.AllocCoTaskMem ()
和Marshal.FreeCoTaskMem()
< /a>.但是,您应该避免这样设计系统。坚持这样一个规则要简单得多:在托管端分配的所有内存都在那里释放,对于本机端也是如此。如果您不遵守该规则,您可能很快就会忘记谁对什么负责。
The golden rule is that you must deallocate from the same heap that was used to allocate the memory.
If you allocate it with
malloc()
, you must deallocate it with thefree()
from the same C RTL. And likewise on the managed side,AllocHGlobal()
should be balanced byFreeHGlobal()
.Now,
AllocHGlobal()
is implemented by calling the Win32 functionLocalAlloc
. So you could free such memory with a call toLocalFree
on the native side. And vice versa.If you want to use a heap that is shared between native and managed, it is more common to use the COM heap. On the native side use
CoTaskMemAlloc()
andCoTaskMemFree()
. On the managed side useMarshal.AllocCoTaskMem()
andMarshal.FreeCoTaskMem()
.However, you should avoid designing the system like this. It is much simpler to stick to a rule that all memory allocated in the managed side is deallocated there, and likewise for the native side. If you don't follow that rule you will likely soon lose track of who is responsible for what.
可能有问题,也可能没有问题——这完全取决于实现。永远不要依赖应用程序功能的实现细节!
因此,我建议不要使用
Marshal.AllocHGlobal()
、malloc()
、Marshal.FreeHGlobal()
和free()
横向。一个例子,如果你使用一个库,你会遇到可怕的麻烦,它会执行某种奇特的
malloc()/free()
魔法 - 你甚至可能不知道这一点。There might or might not be a problem - this is totally implementation-dependant. Never rely on an implementation detail for your app functionality!
So I recommend not to use
Marshal.AllocHGlobal()
,malloc()
,Marshal.FreeHGlobal()
andfree()
crosswise.One example, where you will run into dire trouble is if you use a library, that does some sort of fancy
malloc()/free()
magic - you might even not know that.