c malloc array pointer return in cython

前端 未结 3 1912
感情败类
感情败类 2021-01-02 19:13

How does one to return a malloc array pointer (or numpy array pointer) in cython back to python3, efficiently.

The cython code works perfectly as long as I don\'t re

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 20:04

    Numpy C API

    Your question is similar to this post.

    You can use the function below to pass a C pointer to Numpy array. The memory will be freed automatically when the Numpy array is recycled. If you want free the pointer mamully, you should not set NPY_OWNDATA flag.

    import numpy as np
    cimport numpy as np
    
    cdef pointer_to_numpy_array_complex128(void * ptr, np.npy_intp size):
        '''Convert c pointer to numpy array.
        The memory will be freed as soon as the ndarray is deallocated.
        '''
        cdef extern from "numpy/arrayobject.h":
            void PyArray_ENABLEFLAGS(np.ndarray arr, int flags)
        cdef np.ndarray[np.complex128, ndim=1] arr = \
                np.PyArray_SimpleNewFromData(1, &size, np.NPY_COMPLEX128, ptr)
        PyArray_ENABLEFLAGS(arr, np.NPY_OWNDATA)
        return arr
    

    For reference:

    • PyArray_SimpleNewFromData
    • Numpy Data Type API

    Cython Typed Memoryviews

    Of couse, you can also use cython memoryview.

    import numpy as np
    cimport numpy as np
    
    cdef np.complex128_t[:,:] view =  c_pointer
    numpy_arr = np.asarray(view)
    

    The code above will transfer C pointer to a numpy array. However this would not free memory automaticlly, you have to free the memory by yourself or it would lead to memory leak!

提交回复
热议问题