Creating Custom Allocators

To create a custom allocator, first declare and initialize a structure of type CFAllocatorContext . Initialize the version field to zero and allocate and assign any desired data, such as control information,to the the info field. The other fields of this structure are function pointers described in Implementing Allocator Callbacks, below.

Once you have assigned the proper values to the fields of the CFAllocatorContext structure, invoke the CFAllocatorCreate function to create the allocator object. The second parameter of this function is a pointer to the structure. The first parameter of this function identifies an allocator to use for allocating memory for the new object. If you want to use the allocate callback in the CFAllocateContext structure for this purpose, specify the kCFAllocatorUseContext constant for the first parameter. If you want to use the default allocator, specify NULL in this parameter.

Listing 5 Creating a custom allocator
static CFAllocatorRef myAllocator(void) { static CFAllocatorRef allocator = NULL; if (!allocator) { CFAllocatorContext context = {0, NULL, NULL, (void *)free, NULL, myAlloc, myRealloc, myDealloc, NULL}; context.info = malloc(sizeof(int)); /* The info field points to an int which keeps */ /* track of the number of allocations/deallocations */ *(int *)(context.info) = 0; allocator = CFAllocatorCreate(NULL, &context); } return allocator; }

Implementing Allocator Callbacks


© 1999 Apple Computer, Inc. – (Last Updated 07 September 99)