Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to convert ctypes array to python list?

Tags:

python

ctypes

I was wondering if someone could advise me whether there is a better/faster approach to read data from my C program that outputs two lists of size n. I am using ctypes to call the C program.

The loop I show below works by iterating over a number of scans. For each scan two lists are produced (msX, msY). The c_float data is extracted by using list comprehension loop. Is there a better/faster way to convert the c_float_Array obtained from mzP and mzI to msX and msY?

for scan in xrange(nScans):
    mzP = (c_float * nPoints)() # pointer to list 1, c_float_Array
    mzI = (c_float * nPoints)() # pointer to list 2,  c_float_Array
    mlLib.readData(filePointer, 1, scan, byref(mzP), byref(mzI))
    # The slow part...
    msX = [mzP[i] for i in xrange(nPoints)] # list with mzP data
    msY = [mzI[i] for i in xrange(nPoints)] # list with mzI data

Let me know if my question is not clear. Thanks for your help in advance.

like image 600
munieq11 Avatar asked May 26 '26 08:05

munieq11


2 Answers

I may be missing something, but this works for me:

from ctypes import c_float

arr = (c_float * 3)(1,2,3)
arr[:]
#Result: [1.0, 2.0, 3.0]
like image 182
Jay Avatar answered Jun 01 '26 19:06

Jay


If you prefer, you can convert to an array with np.ndarray:

msX = np.ndarray((nPoints, ), 'f', mzP, order='C')    
msY = np.ndarray((nPoints, ), 'f', mzI, order='C') 
like image 24
Mano-Wii Avatar answered Jun 01 '26 20:06

Mano-Wii