Introduce finalizer module to manage finalization of C resources.
This commit is contained in:
parent
e8c7fcfd32
commit
bc20661343
7 changed files with 110 additions and 40 deletions
|
|
@ -6,6 +6,8 @@ __version__ = '0.9.1'
|
|||
|
||||
|
||||
from weakref import WeakValueDictionary
|
||||
from llvm._utils.finalizer import track as track_resource
|
||||
from llvm._utils.finalizer import OwnerMixin as _OwnerMixin
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
|
|
@ -19,11 +21,26 @@ class LLVMException(Exception):
|
|||
Exception.__init__(self, msg)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Resource Handle
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class Handle(_OwnerMixin):
|
||||
_finalizer = NotImplemented
|
||||
|
||||
def __init__(self, ptr):
|
||||
self.ptr = ptr
|
||||
self._finalizer_track(self.ptr)
|
||||
|
||||
@classmethod
|
||||
def _finalize(cls, ptr):
|
||||
cls._finalizer(ptr)
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Ownables
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class Ownable(object):
|
||||
class Ownable(Handle):
|
||||
"""Objects that can be owned.
|
||||
|
||||
Modules and Module Providers can be owned, i.e., the responsibility of
|
||||
|
|
@ -32,25 +49,21 @@ class Ownable(object):
|
|||
is NOT intended for public use.
|
||||
"""
|
||||
|
||||
def __init__(self, ptr, del_fn):
|
||||
self.ptr = ptr
|
||||
def __init__(self, ptr):
|
||||
Handle.__init__(self, ptr)
|
||||
self.owner = None
|
||||
self.del_fn = del_fn
|
||||
|
||||
def _own(self, owner):
|
||||
if self.owner:
|
||||
raise LLVMException("object already owned")
|
||||
self.owner = owner
|
||||
self._finalizer_untrack(self.ptr)
|
||||
|
||||
def _disown(self):
|
||||
if not self.owner:
|
||||
raise LLVMException("not owned")
|
||||
self.owner = None
|
||||
|
||||
def __del__(self):
|
||||
if not self.owner:
|
||||
self.del_fn(self.ptr)
|
||||
|
||||
self._finalizer_track(self.ptr)
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Dummy owner, will not delete ownee. Be careful.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue