如何从C创建numpy记录数组
在Python中,我可以这样创建新的numpy记录数组:
numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])
那么我该如何在C程序中做到这一点呢?我想我需要调用 PyArray_SimpleNewFromDescr(nd, dims, descr)
,但是我该如何构建一个合适的 PyArray_Descr
,以便作为第三个参数传递给 PyArray_SimpleNewFromDescr
呢?
2 个回答
6
请查看NumPy指南的第13.3.10节。制作描述符的方法有很多种,不过比起直接写[('a', 'i4'), ('b', 'U5')]
要复杂得多。
11
使用 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;
}
感谢 Adam Rosenfield 指出《NumPy指南》的第13.3.10节。