You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ptr.py 1.3KB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738
  1. from ctypes import c_void_p
  2. class CPointerBase:
  3. """
  4. Base class for objects that have a pointer access property
  5. that controls access to the underlying C pointer.
  6. """
  7. _ptr = None # Initially the pointer is NULL.
  8. ptr_type = c_void_p
  9. destructor = None
  10. null_ptr_exception_class = AttributeError
  11. @property
  12. def ptr(self):
  13. # Raise an exception if the pointer isn't valid so that NULL pointers
  14. # aren't passed to routines -- that's very bad.
  15. if self._ptr:
  16. return self._ptr
  17. raise self.null_ptr_exception_class('NULL %s pointer encountered.' % self.__class__.__name__)
  18. @ptr.setter
  19. def ptr(self, ptr):
  20. # Only allow the pointer to be set with pointers of the compatible
  21. # type or None (NULL).
  22. if not (ptr is None or isinstance(ptr, self.ptr_type)):
  23. raise TypeError('Incompatible pointer type: %s.' % type(ptr))
  24. self._ptr = ptr
  25. def __del__(self):
  26. """
  27. Free the memory used by the C++ object.
  28. """
  29. if self.destructor and self._ptr:
  30. try:
  31. self.destructor(self.ptr)
  32. except (AttributeError, ImportError, TypeError):
  33. pass # Some part might already have been garbage collected