6

I'm just trying to start off by creating a numpy array before I even start to write my extension. Here is a super simple program:

#include <stdio.h>
#include <iostream>
#include "Python.h"
#include "numpy/npy_common.h"
#include "numpy/ndarrayobject.h"
#include "numpy/arrayobject.h"

int main(int argc, char * argv[])
{
    int n = 2;
    int nd = 1;
    npy_intp size = {1};
    PyObject* alpha = PyArray_SimpleNew(nd, &size, NPY_DOUBLE);
    return 0;
}

This program segfaults on the PyArray_SimpleNew call and I don't understand why. I'm trying to follow some previous questions (e.g. numpy array C api and C array to PyArray). What am I doing wrong?

Community
  • 1
  • 1
Alex Z
  • 1,449
  • 4
  • 20
  • 29

1 Answers1

6

Typical usage of PyArray_SimpleNew is for example

int nd = 2;
npy_intp dims[] = {3,2};
PyObject *alpha = PyArray_SimpleNew(nd, dims, NPY_DOUBLE);

Note that the value of nd must not exceed the number of elements of array dims[].

ALSO: The extension must call import_array() to set up the C API's function-pointer table. E.g. in Cython:

import numpy as np
cimport numpy as np

np.import_array()  # so numpy's C API won't segfault

cdef make_array():
  cdef np.npy_intp element_count = 100
  return np.PyArray_SimpleNew(1, &element_count, np.NPY_DOUBLE)
Jerry101
  • 12,157
  • 5
  • 44
  • 63
downhillFromHere
  • 1,967
  • 11
  • 11
  • 1
    Right...I was trying to create a 1-D array. Anyways, with your code, I still get a segfault. – Alex Z Aug 26 '14 at 01:42
  • 6
    Yes, sorry about that. The segfault seems to be related to a required call to `import_array()`. I've never tried calling `PyArray_SimpleNew` from `main` so I'm not sure how to fix this. – downhillFromHere Aug 26 '14 at 09:17