Have cffi.buffer() objects hold a reference to another object.
I just got bitten by this:
empty_pixels = ImageSurface('ARGB32', 100, 100).get_data()[:] assert empty_pixels == b'\x00' * (4 * 100 * 100)
.get_data() return a buffer object from
ffi.buffer() base on memory allocated by the surface. On CPython, by the time the buffer is sliced to get a byte string, the surface has been freed and I’m getting garbage from random memory.
ffi.buffer() to take an optional third argument, a Python object that is referenced by the returned buffer. This mechanism would help ensure that the memory pointed to by the buffer stays valid at least as long as the buffer itself.
Without help from CFFI I guess I could do this with a global WeakKeyDictionary but that feel like it shouldn’t be necessary.