Wednesday, April 23, 2008

Elegant Memory Management Ideas

In working on a recent project, involving some callback data in a animation with DirectX and interesting solution to a common problem was presented.  In order to describe the solution correctly, I must setup the scenario.

We have an animation that is loaded from say an X file with the DirectX API.  When using the convenient function to load the X file (D3DXLoadMeshHierarchyFromX) the obvious problem is any callbacks you will require for animation sets will most likely not be stored in the X file.  So we clone the controller/animation sets after the file has been loaded and allocate an array for callback keys/data.

The problem comes in about how to release this memory when complete.  As the data stored here can really be whatever we like, it becomes harder to clean up (as its heap allocated).

The interesting solution that was shown to me was to use COM.  Well, not exactly full COM but the IUknown interface.  Basically we just ensure that our context data object derive from IUknown (and of course implement the required fields).  One of the required methods is Release().  As with all COM objects, memory cleanup revolves around a reference count, and when all references are gone the object remove "itself" from memory.  Also, note we will be required to implement AddRef and QueryInterface as part of derived interface.

Note we are registering a full COM object we are simply using the interface provided by COM as a reference counting mechanism to allow our objects to clean themselves up when it is required.

I thought this was a cool way to use some tried and true COM libraries to solve a very real problem.  :)