Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy arrays type conversion in C

Tags:

python

numpy

swig

I would like to convert the numpy double array to numpy float array in C(Swig). I am trying to use

PyObject *object = PyArray_FROM_OT(input,NPY_FLOAT)

or

PyObject *object = PyArray_FROMANY(input,NPY_FLOAT,0,0,NPY_DEFAULT)

or

PyObject *object = PyArray_FromObject(input,NPY_FLOAT,0,0)

or

PyObject *object = PyArray_ContiguousFromAny(input,NPY_FLOAT,0,0)

But all of them return NULL? Am I missing anything?

like image 989
lakshmesha Avatar asked Jul 15 '26 12:07

lakshmesha


1 Answers

Your approach is correct, yet your assumption about they numpy C API is not. NPY_FLOAT is just an integral constant, yet the functions you posted require the type parameter to be a pointer to a PyArray_Descr struct.

In order to get a type description from a mere type, you can call PyArray_DescrFromType, so your call could look like this:

PyArrayObject* float_array = (PyArrayObject*)PyArray_FromAny(input,PyArray_DescrFromType(NPY_FLOAT64), 0,0, flags);

...with flags being whatever flags you deem meaningful when converting - please have a look at the numpy API, both for correct API invocation and for the meaning of different flags and values.

like image 180
Jim Brissom Avatar answered Jul 20 '26 08:07

Jim Brissom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!