1

I am trying to extend Python 3.6 using C++ on windows, following the official documentation and guide. The Anaconda distribution is used with numpy updated to the latest version. In the project python.h and arrayobject.h has been added to the C++ directories, and python36.lib linked, as advised.

For the code, a simple example which is supposed to create an array with the elements 0,1,2,3, when calling the func1 method:

#include <python.h>
#include <arrayobject.h> 

static PyObject* fun(PyObject* self, PyObject* args)
{
    PyObject *X;
    int x[4] = {0,1,2,3};
    int dims[1];
    dims[0] = 1;
    X = PyArray_SimpleNew(1, dims, NPY_INT64, x);

    return X;
}

static PyMethodDef MyMethod[] = {
    { "func1", fun, METH_VARARGS,nullptr },
    { nullptr, nullptr, 0, nullptr } 
};

static struct PyModuleDef MyModule = {
    PyModuleDef_HEAD_INIT,
    "MyModule", 
    NULL, 
    -1,      
    MyMethod
};

PyMODINIT_FUNC PyInit_MyModule(void)
{
    (void)PyModule_Create(&MyModule);
    import_array();
}

The code builds fine. When I take the resulting .pyd file and import it in Spyder, the kernel crashes. Specifically, the import_array(); command seems to cause the crash, as without it the kernel doesn't crash. However, as the documentation notes, the method crashes then. What is the fix?

Tony
  • 343
  • 1
  • 6
  • 15

1 Answers1

1

It was solved by changing the order:

    PyMODINIT_FUNC PyInit_MyModule(void)
    {
        import_array();
        return PyModule_Create(&MyModule);            
    }

All the documentation seems to concern Python 2.X only, which used different initialization. In python 3, the code needs to modified. (There is a small error also in the creation of the array, but I let it be).

Tony
  • 343
  • 1
  • 6
  • 15