lasso
ArrayManager.hpp
Go to the documentation of this file.
00001 #ifndef ARRAYMANAGER_HPP
00002 #define ARRAYMANAGER_HPP
00003 
00004 #include <cstdlib>
00005 
00006 // Check the array size, and allocate the array if necessary.
00007 // Free the array upon leaving scope unless KEEP_ARRAY
00008 // is invoked.
00009 #define ALLOC_CHECK_ARRAY(array, this_size) \
00010   ArrayManager array ## _manager ( reinterpret_cast<void**>(array), *(array ## _allocated), *(array ## _size), this_size, sizeof(**array), err ); \
00011   if (iBase_SUCCESS != *err) return
00012 
00013 #define ALLOC_CHECK_TAG_ARRAY(array, this_size) \
00014   ArrayManager array ## _manager ( reinterpret_cast<void**>(array), *(array ## _allocated), *(array ## _size), this_size, 1, err ); \
00015   if (iBase_SUCCESS != *err) return
00016 
00017 #define KEEP_ARRAY(array) \
00018   array ## _manager .keep_array()
00019 
00020 // Check the array size, and allocate the array if necessary.
00021 // Do NOT free the array upon leaving scope.
00022 #define ALLOC_CHECK_ARRAY_NOFAIL(array, this_size) \
00023   ALLOC_CHECK_ARRAY(array, this_size); KEEP_ARRAY(array)
00024 
00025 
00026 // Implement RAII pattern for allocated arrays, stolen from iMesh
00027 class ArrayManager
00028 {
00029   void** arrayPtr;
00030 
00031 public:
00032 
00033 
00034   ArrayManager( void** array_ptr,
00035                 int& array_allocated_space,
00036                 int& array_size,
00037                 int count,
00038                 int val_size,
00039                 int* err ) : arrayPtr(0)
00040   {
00041     if (!*array_ptr || !array_allocated_space) {
00042       *array_ptr = std::malloc(val_size * count);
00043       array_allocated_space = array_size = count;
00044       if (!*array_ptr) {
00045         *err = iBase_MEMORY_ALLOCATION_FAILED;
00046         return;
00047       }
00048       arrayPtr = array_ptr;
00049     }
00050     else {
00051       array_size = count;
00052       if (array_allocated_space < count) {
00053         *err = iBase_BAD_ARRAY_DIMENSION;
00054         return;
00055       }
00056     }
00057 
00058     *err = iBase_SUCCESS;
00059   }
00060 
00061   ~ArrayManager()
00062   {
00063     if (arrayPtr) {
00064       std::free(*arrayPtr);
00065       *arrayPtr = 0;
00066     }
00067   }
00068 
00069   void keep_array()
00070     { arrayPtr = 0; }
00071 };
00072 
00073 #endif
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Defines