base class for objects that have a pointer access property that controls access to the underlying c pointer raise an exception if the pointer isn t valid so that null pointers aren t passed to routines that s very bad only allow the pointer to be set with pointers of the compatible type or none null free the memory used by the c object base class for objects that have a pointer access property that controls access to the underlying c pointer initially the pointer is null raise an exception if the pointer isn t valid so that null pointers aren t passed to routines that s very bad only allow the pointer to be set with pointers of the compatible type or none null free the memory used by the c object some part might already have been garbage collected
from ctypes import c_void_p


class CPointerBase:
    

    _ptr = None  
    ptr_type = c_void_p
    destructor = None
    null_ptr_exception_class = AttributeError

    @property
    def ptr(self):
        
        
        if self._ptr:
            return self._ptr
        raise self.null_ptr_exception_class(
            "NULL %s pointer encountered." % self.__class__.__name__
        )

    @ptr.setter
    def ptr(self, ptr):
        
        
        if not (ptr is None or isinstance(ptr, self.ptr_type)):
            raise TypeError("Incompatible pointer type: %s." % type(ptr))
        self._ptr = ptr

    def __del__(self):
        
        if self.destructor and self._ptr:
            try:
                self.destructor(self.ptr)
            except (AttributeError, ImportError, TypeError):
                pass