creating numpy array in c extension segfaults
Asked Answered
G

1

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?

Gratification answered 25/8, 2014 at 21:46 Comment(0)
D
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)
Dunnage answered 26/8, 2014 at 1:1 Comment(2)
Right...I was trying to create a 1-D array. Anyways, with your code, I still get a segfault.Gratification
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.Dunnage

© 2022 - 2024 — McMap. All rights reserved.