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