0

I'm trying to write a c extension for python to speed up some number crunching I'm doing in my project with out having to port the whole thing to C. Unfortunately when I try to return numpy arrays by using my extension function in python it causes segmentation fault 11. Here's a minimal example below.

#include "Python.h"
#include "numpy/arrayobject.h"
#include <math.h>

static PyObject *myFunc(PyObject *self, PyObject *args)
{
    PyArrayObject *out_array;
    int dims[1];
    dims[0] = 2;
    out_array = (PyArrayObject *) PyArray_FromDims(1,dims,NPY_DOUBLE);

    // return Py_BuildValue("i", 1); // if I swap this return value it works
    return PyArray_Return(out_array);
}

static PyMethodDef minExMethiods[] = {
    {"myFunc", myFunc, METH_VARARGS},
    {NULL, NULL}     /* Sentinel - marks the end of this structure */
};

static struct PyModuleDef minExModule = {
    PyModuleDef_HEAD_INIT,
    "minEx",   /* name of module */
    NULL, /* module documentation, may be NULL */
    -1,       /* size of per-interpreter state of the module,
                 or -1 if the module keeps state in global variables. */
    minExMethiods
};

PyMODINIT_FUNC PyInit_minEx(void)
{   
    return PyModule_Create(&minExModule);
}

Can anyone suggest what I might be doing wrong? I'm using conda with a python 3.6 environment on OS X 10.13.6

thanks

1 Answer 1

1

well showing my inexperience here but hopefully useful to others. I needed to call. import_array() in the modules initialisation function to use numpy's c helping functions properly. I also then got errors that PyArray_FromDims was depreciated. the fixed code bellow.

#include "Python.h"
#include "numpy/arrayobject.h"
#include <math.h>

static PyObject *myFunc(PyObject *self, PyObject *args)
{
    PyArrayObject *out_array;
    npy_intp dims[1];
    dims[0] = 2;
    out_array = (PyArrayObject *) PyArray_SimpleNew(1,dims,PyArray_DOUBLE);
    return PyArray_Return(out_array);
}

static PyMethodDef minExMethiods[] = {
    {"myFunc", myFunc, METH_VARARGS},
    {NULL, NULL}     /* Sentinel - marks the end of this structure */
};

static struct PyModuleDef minExModule = {
    PyModuleDef_HEAD_INIT,
    "minEx",   /* name of module */
    NULL, /* module documentation, may be NULL */
    -1,       /* size of per-interpreter state of the module,
                 or -1 if the module keeps state in global variables. */
    minExMethiods
};

PyMODINIT_FUNC PyInit_minEx(void)
{   
    PyObject *module = PyModule_Create(&minExModule);
    import_array();
    return module;
}
Sign up to request clarification or add additional context in comments.

Comments

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.