I have a large (numpy ndarray) object whose memory I want to free as soon as I am finished with it in my Python extension (or I will quickly run out of memory). How can I safely do this?
It seems that in Python, something like del arr
followed by gc.collect()
would work, but I don't want to wait until my function returns. I have also considered ((PyObject*)arr)->ob_type->tp_dealloc((PyObject*)arr); Py_DECREF(arr)
to call the destructor directly, but this seems likely to lead to a segmentation fault further down the line, since I am not sure if I own the reference (I got it from the tuple passed to my function as PyObject* args
).
Another option might be to free the underlying C array with free
, replace the ndarray's data pointer with a different one, and adjust the shape and other ndarray members accordingly. This feels hack-ish, but I am looking through the numpy C API to see if this is really possible.
Any tips would be greatly appreciated. Thanks in advance.