Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty arrays in cython: segfault when calling PyArray_EMPTY

When I try to run the cython code below to generate an empty array, it segfaults.

Is there any way of generating empty numpy arrays in python without calling np.empty()?

cdef np.npy_intp *dims = [3]
cdef np.ndarray[np.int_t, ndim=1] result = np.PyArray_EMPTY(1, dims, 
                                                            np.NPY_INTP, 0)
like image 582
staticd Avatar asked Aug 26 '13 08:08

staticd


1 Answers

You might have solved this a long time ago, but for the benefit of anyone who stumbles across this question while trying to figure out why their cython code segfaults, here's a possible answer.

When you get a segfault when using the numpy C API, the first thing to check is that you have called the function import_array(). That might be the problem here.

For example, here's foo.pyx:

cimport numpy as cnp


cnp.import_array()  # This must be called before using the numpy C API.

def bar():
    cdef cnp.npy_intp *dims = [3]
    cdef cnp.ndarray[cnp.int_t, ndim=1] result = \
        cnp.PyArray_EMPTY(1, dims, cnp.NPY_INTP, 0)
    return result

Here's a simple setup.py for building the extension module:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np


setup(cmdclass={'build_ext': build_ext},
      ext_modules=[Extension('foo', ['foo.pyx'])],
      include_dirs=[np.get_include()])

Here's the module in action:

In [1]: import foo

In [2]: foo.bar()
Out[2]: array([4314271744, 4314271744, 4353385752])

In [3]: foo.bar()
Out[3]: array([0, 0, 0])
like image 123
Warren Weckesser Avatar answered Oct 12 '22 14:10

Warren Weckesser