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

时间:2022-10-26 21:45:12

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

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

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?

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

2 个解决方案

#1


10  

Use PyArray_DescrConverter. Here's an example:

使用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;
}

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

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

#2


5  

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')].

参见NumPy指南,第13.3.10节。有很多不同的方法可以创建一个描述符,虽然它并不像写[('a','i4'),('b','U5')]那么容易。

#1


10  

Use PyArray_DescrConverter. Here's an example:

使用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;
}

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

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

#2


5  

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')].

参见NumPy指南,第13.3.10节。有很多不同的方法可以创建一个描述符,虽然它并不像写[('a','i4'),('b','U5')]那么容易。