NumPy C-API: convert type object to type number

强颜欢笑 提交于 2020-01-02 04:00:07

问题


The function

PyObject* PyArray_TypeObjectFromType(int);

converts the type number for a NumPy scalar type (NPY_BOOL, NPY_BYTE, ...) to the corresponding type object.

How do you do the opposite conversion, from the type object for a NumPy scalar type to the corresponding type number?

Edit: The following code is based on kwatford's answer. It accepts both type objects such as int and numpy.int16, and strings such as "int", u"int" and "int16".

int numpyScalarTypeNumber(PyObject* obj)
{
    PyArray_Descr* dtype;
    if(!PyArray_DescrConverter(obj, &dtype)) return NPY_NOTYPE;
    int typeNum = dtype->type_num;
    Py_DECREF(dtype);
    return typeNum;
}

回答1:


If you can get PyArray_Descr structs rather than PyArray_TypeObjects, you can simply look at the type_num field. The descr structs can be acquired via the type number using PyArray_DescrFromType. If you look at that link, there are also a few more functions for converting various things into descr structs. They're probably more useful in general than the type objects, and they contain references to their types as well.



来源:https://stackoverflow.com/questions/8477122/numpy-c-api-convert-type-object-to-type-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!