User Tools

Site Tools


Allocator Interface

The SpeedTree SDK features an allocation interface where all heap allocations made by the SDK libraries are funneled through a single interface. Setting up the memory allocator is done in this way:

///////////////////////////////////////////////////////////////////////  
//  class CAllocator
//
//  This is the base class as defined in Core/Allocator.h.
 
class CAllocator
{
public:
virtual           ~CAllocator( ) { }
 
virtual void*     Alloc(size_t BlockSize) = 0;
virtual void      Free(void* pBlock) = 0;
};
 
/////////////////////////////////////////////////////////////////////// 
//  class CReferenceAllocator
//
//  This is an example application-level allocator object, derived from the
//  interface provided by SpeedTree. 
 
class CReferenceAllocator : public SpeedTree::CAllocator
{
public:
 
    void* Alloc(size_t BlockSize, size_t)
    {
        void *pBlock = malloc(BlockSize);
 
        if (pBlock == 0) // did malloc fail?
            throw std::bad_alloc( ); // ANSI/ISO compliant behavior
 
        return pBlock;
    }
 
    void Free(void* pBlock)
    {
        if (pBlock)
            free(pBlock);
    }
};
 
//
//  Below follows two different ways to pass an allocator object to the SDK 
//
 
//
//  Method #1
//
//  Create a global or static allocator object and pass it into the SDK before
//  main is called.  Note that the CAllocatorInterface object constructor
//  takes a pointer to the allocator object.
 
static CReferenceAllocator g_cMyAllocator;
static SpeedTree::CAllocatorInterface g_cAllocatorInterface(g_cMyAllocator);
 
/////////////////////////////////////////////////////////////////////// 
//  main
//
//  Method #2
//
//  Use the SpeedTree::CAllocatorInterface class to enable or disable the
//  allocator object at any point.
 
void main(void)
{
    ...
 
   // don't use a custom allocator
   CAllocatorInterface cOff(NULL);
 
    ... // do something
 
    // turn the allocator back on
   CAllocatorInterface cOn(g_cMyAllocator);
}

All heap allocations made by any of the classes in the SpeedTree SDK are passed through the interface. The reference application also shows how to continue to do this for example SpeedTree-related objects.