[Numpy-discussion] "aligned" matrix / ctypes

Zachary Pincus zachary.pincus@yale....
Wed Apr 23 14:10:43 CDT 2008


Hello all,

I need to allocate a numpy array that I will then pass to a camera  
driver (via ctypes) so that the driver can fill the array with pixels.  
The catch is that the driver requires that rows of pixels start at 4- 
byte boundaries.

The sample C++ code given for allocating memory for this is (pixels  
are unsigned shorts):

// Two bytes for each pixel, then round
// up to the next multiple of four.
long width_bytes = ( ( 2 * width_pixels ) + 3 ) & -4;
long allocated_size = width_bytes * height;
unsigned char* image_data = new unsigned char[allocated_size];
I could make an empty uint8 numpy array of the required shape  
(allocated_size,) and adjust its dtype, shape, and strides to get the  
desired result. I'd then feed the array's ctypes data attribute to the  
driver to get filled in. Alternately I could allocate the data buffer  
via ctypes and then construct an array around it.

Is either option better? How does one construct a numpy array around a  
ctypes memory object? Can the array "take over" the memory management  
for the buffer?

Thanks for any suggestions,
Zach


More information about the Numpy-discussion mailing list