0

Code (based on Numpy C-Api example gives a SegFault. The link to the tutorial they were following is dead, and I haven't found a good tutorial):

#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_API_VERSION

#include "numpy/arrayobject.h"

int main()
{

   Py_Initialize();
   import_array();

   int typenum;
   PyArrayObject *alpha;
   PyObject *a = NULL;
   int n = 100;
   int nd = 1;
   int dims[nd];
   dims[0] = n;
   a= PyArray_FromDims(nd, dims, NPY_DOUBLE);
   alpha = (PyArrayObject*) a;

   typenum = PyArray_DIMS(alpha)[0];
   printf("%i",typenum);
   PyRun_SimpleString("print 'Hello Python C/API'");
   Py_Finalize();
   return 0;
}
gcc -g main1.cpp -I/.../include/python2.7 -I/.../numpy/numpy/core/include -lpython2.7 -lstdc++; ./a.out

Gives a segfault on a= PyArray_FromDims(nd, dims, NPY_DOUBLE);.

I'm in a virtualenvironment, which has ben activated. The "..." gives the path to my virtual environment where numpy lives as a subdirectory, and has been installed using pip install -e numpy.

Community
  • 1
  • 1
honi
  • 946
  • 1
  • 7
  • 18
  • Possible dup of http://stackoverflow.com/questions/7774524/segfault-when-trying-to-write-to-a-numpy-array-created-within-a-c-extension. Another link that might help: https://sourceforge.net/p/numpy/mailman/message/5700519/ – CristiFati Jun 24 '16 at 00:13
  • The definition of the macro `import_array()` is `#define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return NUMPY_IMPORT_ARRAY_RETVAL; } }`. So you should check for the return value of `_import_array()` being negative. – Warren Weckesser Jun 24 '16 at 01:03
  • it still doesn't work if I _import_array() to import_array() – honi Jun 24 '16 at 03:39

0 Answers0