[Numpy-discussion] segfault in PyArray_FromDims

Juerg Tschirren juerg-tschirren at uiowa.edu
Sun Jul 1 14:23:17 CDT 2001


I did some experimenting with the NumPy C API. I wrote two functions.
One for processing a NumPy array in C++ and the other one for
generating a NumPy array in C++. The processing function work perfectly
fine. But in the array-generating function I get a segmentation fault
whenever I call PyArray_FromDims. I used swig for generating the wrapper
functions.

The two src-files (numPyExt.i and numPyExt.cc):

--- begin numPyExt.i -------------------------------------------------
%module numPyExt

%{
  #include <iostream.h>
  #include <Python.h>
  #include <Numeric/arrayobject.h>
%}

%init %{
  import_array();
%}

%typemap(python,in) double * {
  PyArrayObject *py_arr;

  if(!PyArray_Check($source)) {
    PyErr_SetString(PyExc_TypeError, "Not a NumPy array");
    return NULL;
  }

  if (PyArray_ObjectType($source,0) != PyArray_DOUBLE) {
    PyErr_SetString(PyExc_ValueError, "Array must be of type double");
    return NULL;
  }

  py_arr = (PyArrayObject*) \
    (PyArray_ContiguousFromObject($source, PyArray_DOUBLE, 1, 1));

  if (py_arr->nd != 1) {
    PyErr_SetString(PyExc_TypeError, "Array must be 1D");
    return NULL;
  }

  $target = (double*)(py_arr->data);
}

extern  PyObject* createArray();
extern  void processArray(double* pdInArray);
--- end numPyExt.i ---------------------------------------------------

--- begin numPyExt.cc ------------------------------------------------
#include <iostream.h>
#include <Python.h>
#include <Numeric/arrayobject.h>
//------
PyObject* createArray() {
  PyArrayObject* retArray;
  int iDimensions[3] = {10, 10, 10};
  cout << "before PyArray_FromDims" << endl << flush;
  retArray = (PyArrayObject*)PyArray_FromDims(3, iDimensions, PyArray_INT);
  cout << "after PyArray_FromDims" << endl << flush;

  return PyArray_Return(retArray);
}
//------
void processArray(double* pdInArray) {
  cout << *pdInArray << " " << *(pdInArray+1) << " " << *(pdInArray+2)
<< endl;
}
--- end numPyExt.cc --------------------------------------------------

Compiled with:
  g++ -c  -I/usr/local/include/python2.0 -I/usr/local/lib/python2.0/site-packages -O2 numPyExt.cc
  swig -python -c++ numPyExt.i
  g++ -c -O2 numPyExt_wrap.c -DOS_LINUX -DHAVE_CONFIG_H -I. -I/usr/local/include/python2.0 -I/usr/local/lib/python2.0/site-packages -I/usr/local/lib/python2.0/config
  g++ -W1,--heap,50000,--stack,100000 -O2 -shared numPyExt.o numPyExt_wrap.o -lstdc++ -o numPyExt.so


The Python test code I am using:

  import Numeric, numPyExt

  vec = Numeric.array((1.23, 4.56, 7.89))
  numPyExt.processArray(vec)                 # works fine

  a = numPyExt.createArray()                 # seg fault here
  print a


I am using NumPy v20.0.0, Python 2.1, and gcc 2.95.2 on a Linux 2.2.16
sytem.

Does anybody have an idea what's causing this problem?

Juerg






More information about the Numpy-discussion mailing list