0

I have allocated an array and cast it using the Python ctypes module:

    dataC = ctypes.cast(crt.malloc(size), ctypes.POINTER(ctypes.c_ubyte))

in order to get byte data from a C library:

    someClib.getData(handle, dataC)

Now this array is actually an array of C float types. How can I convert it to a Python list of floating type numbers?

1 Answer 1

5

You can cast to a pointer to float:

floatPtr = ctypes.cast(dataC, ctypes.POINTER(ctypes.c_float))

And then use a list comprehension, for example, to pull out the floats:

floatList = [floatPtr[i] for i in range(arrayLength)]

Now, only you know the value of arrayLength but it seems plausible to me that it is equal to size / ctypes.sizeof(ctypes.c_float).

Sign up to request clarification or add additional context in comments.

3 Comments

Backing up a step, allocate the float array to begin with, i.e. dataC = (ctypes.c_float * arrayLength)(). It's sized, so there's no need for a list comprehension. At least use dataC = (ctypes.c_ubyte * size)(). Using the C runtime's malloc is usually the wrong approach.
@eryksun That sounds sensible. I was answering naively the question as asked.
@eryksun I'll try your approach - it would simplify the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.