Skip to content
Advertisement

Force NumPy ndarray to take ownership of its memory in Cython

Following this answer to “Can I force a numpy ndarray to take ownership of its memory?” I attempted to use the Python C API function PyArray_ENABLEFLAGS through Cython’s NumPy wrapper and found it is not exposed.

The following attempt to expose it manually (this is just a minimum example reproducing the failure)

JavaScript

fails with a compile error:

JavaScript

My question: Is this the right approach to take in this case? If so, what am I doing wrong? If not, how do I force NumPy to take ownership in Cython, without going down to a C extension module?

Advertisement

Answer

You just have some minor errors in the interface definition. The following worked for me:

JavaScript

This is my setup.py file:

JavaScript

Build with python setup.py build_ext --inplace. Then verify that the data is actually owned:

JavaScript

Among others, you should see OWNDATA : True.

And yes, this is definitely the right way to deal with this, since numpy.pxd does exactly the same thing to export all the other functions to Cython.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement