'PyArray_Check / PyArray_CheckExact gives segmentation fault

In c++, I define the following module:

#include <boost/python.hpp>
#include <numpy/arrayobject.h>

bool foo(PyObject *obj)
{
    if (!PyArray_CheckExact(obj))
        return false;

    PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(obj);

    if (PyArray_NDIM(arr) != 2)
        return false;

    return true;    
}

BOOST_PYTHON_MODULE(pyMod)
{
    using namespace boost::python;

    import_array();

    def("foo", foo);
}

In python, I do the following

import numpy as np
import myMod

if __name__ == "__main__":
    arr = np.zeros(shape=(100, 100), dtype=np.uint8)

    myMod.foo(arr)

This gives segmentation fault when executing the call to PyArray_CheckExact. Removing the check, the function runs fine and the cast is successfull.

I tried this:

bool foo(PyObject *obj)
{
    if (obj->ob_type->ob_type != &PyArray_Type)
        return false;

    PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(obj);

    if (PyArray_NDIM(arr) != 2)
        return false;

    return true;    
}

Which also segfaults. It seems like something in the Numpy API which is not correctly initialized. I use Anaconda2 32bit on windows.

Any ideas on why this segfaults?



Solution 1:[1]

You need to first call

import_array();

Within your C code. If not this will cause a segfault.

This is the issue that impacted me.

There are only 2 ways this can cause problems.

  1. PyArrayObj is NULL
  2. import_array() has not been called.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yunnosch