2

With this code I am trying to create a numpy array from a malloc'ed c pointer, inspired by a blog post from Gaël Varoquaux.

The line that creates the array seems to lead to an invalid memory access as it crashes the kernel. What did I do wrong?

%%cython -f

from libc.stdlib cimport malloc
import numpy as np
cimport numpy as np

cdef array_from_pointer(double* ptr, int size):
    cdef np.npy_intp shape_c[1]
    shape_c[0] = <np.npy_intp> size
    ndarray = np.PyArray_SimpleNewFromData(1, shape_c, np.NPY_FLOAT64, ptr)
    return ndarray


cdef N = 12
cdef double* ptr = <double*> malloc(sizeof(double)*N)

array_from_pointer(ptr, N)
1

1 Answer 1

0

Before using numpy's Array API, you need to call np.import_array():

%%cython -f

from libc.stdlib cimport malloc
import numpy as np
cimport numpy as np
np.import_array()

cdef array_from_pointer(double* ptr, int size):
    cdef np.npy_intp shape_c[1]
    shape_c[0] = <np.npy_intp> size
    ndarray = np.PyArray_SimpleNewFromData(1, shape_c, np.NPY_FLOAT64, ptr)
    return ndarray


cdef N = 12
cdef double* ptr = <double*> malloc(sizeof(double)*N)

array_from_pointer(ptr, N)

Failing to do so causes the segmentation fault that crashes the ipython kernel.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.