summaryrefslogtreecommitdiff
path: root/cffi/gc_weakref.py
blob: 31621fd9502fced6bdcffab1e64cd176d074906a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from weakref import ref


class GcWeakrefs(object):
    # code copied and adapted from WeakKeyDictionary.

    def __init__(self, ffi):
        self.ffi = ffi
        self.data = data = {}
        def remove(k):
            destructor, cdata = data.pop(k)
            destructor(cdata)
        self.remove = remove

    def build(self, cdata, destructor):
        # make a new cdata of the same type as the original one
        new_cdata = self.ffi.cast(self.ffi.typeof(cdata), cdata)
        self.data[ref(new_cdata, self.remove)] = destructor, cdata
        return new_cdata