CFFI: keep cdata alive as long as buffer is referencing it

155 Views Asked by At

I have wrapped C library via CFFI and I want my Python objects to provide buffer interface to underlying C data. I have something like this:

class Series(object):
    def __init__(self):
        self._series = ffi.gc(new_series(), free_series)
        self.rawdata = ffi.buffer(self._series.data, self._series.len)

The problem is that self.rawdata doesn't keep self._series alive. I get segfault if I do something like:

var = Series()
var = series.rawdata # Series object is garbage collected and free_series is called
print(bytes(var)) # at this point memory pointed by buffer is deallocated

I tried to workaround this by using ffi.gc to object returned by ffi.buffer, but sadly the type returned by ffi.buffer is not accepted.

0

There are 0 best solutions below