2

I'm making a C extension for Python that returns a numpy array.

I do something like this

int *d = malloc(...
//set values in d
return PyArray_SimpleNewFromData(...., d);

When the newly created array is garbage collected, I want to ensure the memory in d is also deallocated.

What is the best way to do this?

Mike
  • 58,961
  • 76
  • 175
  • 221
  • See related question [Creating a numpy array in C from an allocated array is causing memory leaks](https://stackoverflow.com/q/28905659/1782792) (and linked articles). Seems [`NPY_ARRAY_OWNDATA`](https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.NPY_ARRAY_OWNDATA) may help? – jdehesa Apr 29 '19 at 09:12
  • 1
    Poking at the source code for numpy a little, it looks like `NPY_ARRAY_OWNDATA` means the memory area was allocated with numpy's internal allocator, and one shouldn't use it for memory allocated directly by `malloc`. An alternative may be [`PyArray_SetBaseObject`](https://docs.scipy.org/doc/numpy-1.13.0/reference/c-api.array.html#c.PyArray_SetBaseObject); you'd need to define a shim Python object that remembers `d` and calls `free(d)` on destruction. (This is a comment rather than an answer because I don't know if it will work.) – zwol Apr 29 '19 at 12:05

0 Answers0