Skip to content

Instantly share code, notes, and snippets.

@uranusjr
Last active August 29, 2015 14:23
Show Gist options
  • Save uranusjr/41a5ce12ff2c531bc3dd to your computer and use it in GitHub Desktop.
Save uranusjr/41a5ce12ff2c531bc3dd to your computer and use it in GitHub Desktop.
Wrapper implementing RAII idiom for ctypes objects.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import weakref
__all__ = ['CObjectWrapper']
# Keeps a reference to all wrapper instances so that we can dealloc them when
# we need to.
_tracked_refs = {}
def _run_finalizer(ref):
"""Internal weakref callback to run finalizers.
"""
del _tracked_refs[id(ref)]
finalizer = ref.finalizer
wrapped = ref.wrapped
finalizer(wrapped)
# Must subclass `weakref.ref` so that we can add attributes to it.
class _Ref(weakref.ref):
pass
class CObjectWrapper(object):
"""C object wrapper using a weakref for memory management.
Based on `http://code.activestate.com/recipes/577242`.
:param wrapped: A C object to be wrapped. This will be accessible with
`self._wrapped`.
:param finalizer: A callable that takes one argument `wrapped`.
"""
def __init__(self, wrapped, finalizer):
self._wrapped = wrapped
ref = _Ref(self, _run_finalizer)
ref.wrapped = wrapped
ref.finalizer = finalizer
_tracked_refs[id(ref)] = ref
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment