Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!!

like image 944
Wang Yudong Avatar asked Oct 14 '12 04:10

Wang Yudong


1 Answers

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~~

like image 162
Wang Yudong Avatar answered Oct 21 '22 07:10

Wang Yudong