How to check ndarray data type in C

Can someone tell me how to check the ndarray data type that was passed in C code?

In a specific example, I would like to name another function if the data type of the array is float32 or double/float64 . So something like

 if( Dtype(MyArray) == NPY_FLOAT ) { DoSomething_float( MyArray ); } else { DoSomething_double( MyArray ); } 

I already found

 PyTypeNum_ISFLOAT(num) PyDataType_ISFLOAT(descr) PyArray_ISFLOAT(obj) 

In the numpy C API, but I don't understand how to use them. I already tried to find an instructive example, but did not find any.

+6
source share
2 answers

you are almost there since you are looking for PyArray_TYPE :

 int typ=PyArray_TYPE(MyArray); switch(typ) { case NPY_FLOAT: DoSomething_single(MyArray); break; case NPY_DOUBLE: DoSomething_double(MyArray); break; default: error("unknown type %d of MyArray\n", typ); } 
+7
source

The long, confusing way to do this if you are dealing with PyArrayObject* arr is to check arr->descr->type or arr->descr->type_num , which contains:

char PyArray_Descr.type Traditional character code indicating data type

int PyArray_Descr.type_num number that uniquely identifies a given type. For new data types, this number is assigned when the data type is registered.

As @umlauete's answer points out, there are cleaner ways to include this in your code, but it’s always good to know that in your PyArrayObject and PyArray_Descr . And always "read documents , Luke!"

+4
source

All Articles