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?

1 Answer 1

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:

This function must be called in the initialization section of a module that will make use of the C-API. It imports the module where the function-pointer table is stored and points the correct variable to it.

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Right...I was trying to create a 1-D array. Anyways, with your code, I still get a segfault.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.