I'm trying to use the Numpy C API to create Numpy arrays in C++, wrapped in a utility class. Most things are working as expected, but whenever I try to create an array using one of the functions taking a PyArray_Descr*, the program instantly segfaults. What is the correct way to set up the PyArray_Descr for creation?
An example of code which isn't working:
PyMODINIT_FUNC
PyInit_pysgm()
{
import_array();
return PyModule_Create(&pysgmmodule);
}
// ....
static PyAry zerosLike(PyAry const& array)
{
PyArray_Descr* descr = new PyArray_Descr;
Py_INCREF(descr); // creation function steals a reference
descr->type = 'H';
descr->type_num = NPY_UINT16;
descr->kind = 'u';
descr->byteorder = '=';
descr->alignment = alignof(std::uint16_t);
descr->elsize = sizeof(std::uint16_t);
std::vector<npy_intp> shape {array.shape().begin(), array.shape().end()};
// code segfaults after this line before entering PyAry constructor
return PyAry(PyArray_Zeros(shape.size(), shape.data(), descr, 0));
}
(testing with uint16).
I'm not setting the typeobj field, which may be the only problem, but I can't work out what the appropriate value of type PyTypeObject would be.
Edit: This page lists the ScalarArray PyTypeObject instances for different types. Adding the line
descr->typeobj = &PyUShortArrType_Type;
has not solved the problem.