9

On the Python side, I can create new numpy record arrays as follows:

numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])

How do I do the same from a C program? I suppose I have to call PyArray_SimpleNewFromDescr(nd, dims, descr), but how do I construct a PyArray_Descr that is appropriate for passing as the third argument to PyArray_SimpleNewFromDescr?

2 Answers 2

11

Use PyArray_DescrConverter. Here's an example:

#include <Python.h>
#include <stdio.h>
#include <numpy/arrayobject.h>

int main(int argc, char *argv[])
{
     int dims[] = { 2, 3 };
     PyObject *op, *array;
     PyArray_Descr *descr;

     Py_Initialize();
     import_array();
     op = Py_BuildValue("[(s, s), (s, s)]", "a", "i4", "b", "U5");
     PyArray_DescrConverter(op, &descr);
     Py_DECREF(op);
     array = PyArray_SimpleNewFromDescr(2, dims, descr);
     PyObject_Print(array, stdout, 0);
     printf("\n");
     Py_DECREF(array);
     return 0;
}

Thanks to Adam Rosenfield for pointing to Section 13.3.10 of the Guide to NumPy.

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

Comments

6

See the Guide to NumPy, section 13.3.10. There's lots of different ways to make a descriptor, although it's not nearly as easy as writing [('a', 'i4'), ('b', 'U5')].

2 Comments

Thanks, the Guide mentioned PyArray_DescrConverter, which works. I've posted an example as a separate answer, as it doesn't fit in a comment.
@JoelVroom: I don't know what happened to the original link, but I was able to find another link to the same document easily enough.

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.