CoTaskMemAlloc 的用法? [英] Usage of CoTaskMemAlloc?
问题描述
什么时候使用 CoTaskMemAlloc 合适?谁能举个例子?
When is it appropriate to use CoTaskMemAlloc? Can someone give an example?
推荐答案
天哪,我不得不为这个考虑一段时间 -- 我已经用 ATL 完成了大量的小规模 COM 编程,但很少有使用它.
Gosh, I had to think for a while for this one -- I've done a fair amount of small-scale COM programming with ATL and rarely have had to use it.
我想到了一种情况:Windows Shell 扩展.如果您正在处理一组文件系统对象,您可能必须处理 PIDLs(指向 ID 列表的指针).这些是奇怪的小文件系统对象抽象,它们需要使用 COM-aware 分配器(例如 CoTaskMemAlloc
)显式分配/解除分配.还有一个替代方案,IMalloc
从 SHGetMalloc
(已弃用)或 CoGetMalloc
获得的接口指针——它只是一个抽象层使用,因此您的代码不会绑定到特定的内存分配器,可以使用任何合适的分配器.
There is one situation though that comes to mind: Windows Shell extensions. If you are dealing with a set of filesystem objects you might have to deal with PIDLs (pointer to an ID list). These are bizarre little filesystem object abstractions and they need to be explicitly allocated/deallocated using a COM-aware allocator such as CoTaskMemAlloc
. There is also an alternative, the IMalloc
interface pointer obtained from SHGetMalloc
(deprecated) or CoGetMalloc
-- it's just an abstraction layer to use, so that your code isn't tied to a specific memory allocator and can use any appropriate one.
使用 CoTaskMemAlloc
或 IMalloc
而不是 malloc()
的要点是内存分配/释放需要是"COM-aware",以便其分配和解除分配在运行时一致执行,即使分配和解除分配是由完全不相关的代码完成的(例如,Windows 分配内存,将其传输到稍后解除分配的 C++ 代码,或您的 C++ 代码)分配,将其转移到其他人的 VB 代码,稍后释放).malloc()
和 new
都不能与系统的运行时堆互操作,因此您不能使用它们来分配内存以传输到其他 COM 对象,或从其他 COM 对象接收内存并释放.
The point of using CoTaskMemAlloc
or IMalloc
rather than malloc()
is that the memory allocation/deallocation needs to be something that is "COM-aware" so that its allocation and deallocation are performed consistently at run-time, even if the allocation and deallocation are done by completely unrelated code (e.g. Windows allocates memory, transfers it to your C++ code which later deallocates, or your C++ code allocates, transfers it to someone else's VB code which later deallocates). Neither malloc()
nor new
are capable of interoperating with the system's run-time heap so you can't use them to allocate memory to transfer to other COM objects, or to receive memory from other COM objects and deallocate.
这篇关于CoTaskMemAlloc 的用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!