Converting float * to numpy array

4,441 views
Skip to first unread message

Lionel Data

unread,
Jun 14, 2010, 12:38:22 PM6/14/10
to cython...@googlegroups.com
Hi,
I find myself quite helpless in front of such a trivial case. The worst is that it seems I can't find the answer in any tutorial, though I'm quite it is out there :(

Anyway, here is my simple problem:
I have a C function that returns a float *, and I want to build a numpy array with it, and return it to python.

I have some thing like:

cimport numpy as np

cdef float *pfArray = my_c_function()
cdef np.ndarray myarray
# Well I'm quite lost here

Thanks,

Lionel

luper rouch

unread,
Jun 14, 2010, 5:33:02 PM6/14/10
to cython...@googlegroups.com
2010/6/14 Lionel Data <lione...@gmail.com>:

You can simply iterate over your C array and copy the values to the
numpy array :

myarray = np.empty(num_elements)
for i in range(num_elements):
myarray[i] = pfArray[i]

Daily, Jeff A

unread,
Jun 15, 2010, 1:33:40 AM6/15/10
to cython...@googlegroups.com
>> Anyway, here is my simple problem:
>> I have a C function that returns a float *, and I want to build a numpy
>> array with it, and return it to python.
>>
>> I have some thing like:
>>
>> cimport numpy as np
>>
>> cdef float *pfArray = my_c_function()
>> cdef np.ndarray myarray
>> # Well I'm quite lost here
>>
>
> You can simply iterate over your C array and copy the values to the
> numpy array :
>
> myarray = np.empty(num_elements)
> for i in range(num_elements):
> myarray[i] = pfArray[i]

What about numpy.frombuffer()? I've used that function successfully with a ctypes array.
import numpy as np
import ctypes
buffer = (ctypes.c_float * 100)
# do something with buffer
a = np.frombuffer(buffer, np.float32)

Lionel Data

unread,
Jun 15, 2010, 3:55:56 AM6/15/10
to cython...@googlegroups.com
Thanks a lot.

Lionel

2010/6/15 Daily, Jeff A <jeff....@pnl.gov>

Dag Sverre Seljebotn

unread,
Jun 15, 2010, 3:59:16 AM6/15/10
to cython...@googlegroups.com
Have a look at docs.scipy.org, in the NumPy docs, search for
PyArray_SimpleNewFromData (there's examples on this mailing list if you
search for that name, e.g. on gmane.org.)

That will set up an array pointing to the SAME memory. You then need to
.copy() it if you don't want that; otherwise you need to make sure the
memory is freed when the array is freed, which is done through creating
a cdef class (again, there's examples in the mailing list archives
somewhere...)

Dag Sverre

Lionel Data

unread,
Jun 18, 2010, 6:41:53 AM6/18/10
to cython...@googlegroups.com
2010/6/15 Dag Sverre Seljebotn <da...@student.matnat.uio.no>

That is most helpful, thanks a lot.

Lionel
Reply all
Reply to author
Forward
0 new messages