Created
September 11, 2018 17:46
-
-
Save pydemo/b4caf7cbb47a91fdd55b6c4334295601 to your computer and use it in GitHub Desktop.
cleanup of C arrays in Cython
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| cdef class _finalizer: | |
| cdef void *_data | |
| def __dealloc__(self): | |
| print "_finalizer.__dealloc__" | |
| if self._data is not NULL: | |
| free(self._data) | |
| cdef void set_base(cnp.ndarray arr, void *carr): | |
| cdef _finalizer f = _finalizer() | |
| f._data = <void*>carr | |
| cnp.set_array_base(arr, f) | |
| def make_matrix(int nrows, int ncols): | |
| cdef float *mat = make_matrix_c(nrows, ncols) | |
| cdef float[:, ::1] mv = <float[:nrows, :ncols]>mat | |
| cdef cnp.ndarray arr = np.asarray(mv) | |
| set_base(arr, mat) | |
| return arr | |
| #setup |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from distutils.core import setup, Extension | |
| from Cython.Build import cythonize | |
| from numpy import get_include | |
| ext = Extension("numpy_cleanup", ["numpy_cleanup.pyx"], | |
| include_dirs=['.', get_include()]) | |
| setup(name="numpy_cleanup", | |
| ext_modules = cythonize(ext)) | |
| #python setup.py build_ext -i | |
| $ ipython --no-banner | |
| In [1]: import numpy_cleanup | |
| In [2]: arr = numpy_cleanup.make_matrix(100, 100) | |
| In [3]: arr.base | |
| Out[3]: <numpy_cleanup._finalizer at 0x100284eb8> | |
| In [4]: %reset | |
| Once deleted, variables cannot be recovered. Proceed (y/[n])? y | |
| _finalizer.__dealloc__ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment