1

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.

1 Answer 1

4

Try using

descr = PyArray_DescrFromType(NPY_UINT16);

I've only recently been writing against the numpy C-API, but from what I gather the PyArray_Descr is basically the dtype from python-land. You should building these yourself and use the FromType macro if you can.

Sign up to request clarification or add additional context in comments.

1 Comment

Whoops - I meant to come back to this - you're right, this is the answer I found.

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.