Python – Turning ctypes data into python string as quickly as possible


I'm trying to write a video application in PyQt4 and I've used Python ctypes to hook into an old legacy video decoder library. The library gives me 32-bit ARGB data and I need to turn that into a QImage. I've got it working as follows:

# Copy the rgb image data from the pointer into the buffer
memmove(self.rgb_buffer, self.rgb_buffer_ptr, self.buffer_size)

# Copy the buffer to a python string
imgdata = ""
for a in self.rgb_buffer:
    imgdata = imgdata + a

# Create a QImage from the string data
img = QImage(imgdata, 720, 288, QImage.Format_ARGB32)

The problem is that ctypes outputs the data as type "ctypes.c_char_Array_829440" and I need to turn it into a python string so that I can construct a QImage. My copying mechanism is currently taking almost 300ms per image so it's painfully slow. The decode and display part of the process is only taking about 50ms.

Can anyone think of any cunning shortcuts I can take to speed up this process and avoid the need to copy the buffer twice as I'm currently doing?

Best Solution

The ctypes.c_char_Array_829400 instance has the property .raw which returns a string possibly containing NUL bytes, and the property .value which returns the string up to the first NUL byte if it contains one or more.

However, you can also use ctypes the access the string at self.rgb_buffer_ptr, like this: ctypes.string_at(self.rgb_buffer_ptr, self.buffer_size); this would avoid the need for the memmove call.