Wang Yudong
Wang Yudong

Reputation: 125

error occurs when I write my own C extension for numpy

I'm trying to write a C extension for numpy to do some calculation with big arrays, but I get a big problem when I use "PyArray_SimpleNew" or "PyArray_FromDims" to get a PyArrayObject . here is my code:

#include<stdio.h>
#include "Python.h"
#include"arrayobject.h"

static PyObject *MyExtGFV(PyObject *self, PyObject *args)
{
    npy_intp dims = 1;
    PyArray_SimpleNew(1, &dims, PyArray_FLOAT32);
    retuurn Py_BuildValue("i", 1);
}
static PyMethodDef my_ext_methods[] = 
{
    {"GFV", MyExtGFV, METH_VARARGS, "used to generate feature vectors"},
    {NULL, NULL}
}

PyMODINIT_FUNC initMyExt(void)
{
    Py_InitModule("MyExt", my_ext_methods);
}

in order to debug it, I have delete most of my code in the function MyExtGFV(), only leave

PyArray_SimpleNew(1, &dims, PyArray_FLOAT32);   

in it, but when I import it and use it in my python code, it says that "python has stopped working". I have googled this problem for a long time, but it seems that no one else have the same problem, it almost drives me crasy, any help will be appreciated!!!

Upvotes: 5

Views: 920

Answers (1)

Wang Yudong
Wang Yudong

Reputation: 125

OK, finally I get it, the init function should be written like this:

PyMODINIT_FUNC initMyExt(void)
{
    Py_InitModule("MyExt", my_ext_methods);
    import_array();
}

"import_array();" is necessary for numpy, thank goodness~~

Upvotes: 6

Related Questions