如何从C创建一个numpy记录数组

Veb*_*osa 8 c python numpy

在Python方面,我可以创建新的numpy记录数组,如下所示:

numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])
Run Code Online (Sandbox Code Playgroud)

我如何从C程序中做同样的事情?我想我必须打电话PyArray_SimpleNewFromDescr(nd, dims, descr),但我如何构建一个PyArray_Descr适合作为第三个参数传递的PyArray_SimpleNewFromDescr

Veb*_*osa 10

使用PyArray_DescrConverter.这是一个例子:

#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;
}
Run Code Online (Sandbox Code Playgroud)

感谢Adam Rosenfield指出NumPy指南的第13.3.10节.


Ada*_*eld 5

参见NumPy指南,第13.3.10节.制作描述符的方法有很多种,尽管它并不像写作那么容易[('a', 'i4'), ('b', 'U5')].