ctypes, arrays and pointers

Thomas Heller theller at python.net
Fri Oct 6 15:09:37 EDT 2006


Richard Jones schrieb:
> Does anyone know how to do the equivalent of this using ctypes?
> 
>     image_data = malloc(width * height * components);
>     row_pointers = png_get_rows(png_ptr, info_ptr);
>     for (y = 0; y < height; y++)
>         memcpy(&image_data[width * components * y],
>                row_pointers[height-y-1],
>                width * components);
> 
> That is, I need to get the address of a location *within* an allocated
> array. This is what I've got:
> 
>     image_data = create_string_buffer(width * height * components)
>     address = addressof(image_data)
>     row_pointers = libpng.png_get_rows(png_ptr, info_ptr)
>     for y in xrange(height):
>         row = string_at(address +  width * components * y)
>         memmove(row, row_pointers[height-y-1], width * components)
> 
> but that's not correct. Either the addressof() or string_at() are not
> working according to my understanding from the docs, because that code
> segfaults. FWIW, I also tried:
> 
>     row = image_data + width * components * y
> 
> but you can't add an int to a c_char_Array_2415600.

This feature request has now come up the second time, so I guess I will
have to find a solution for it.  Someone suggested a byref_at(obj, offset) method
which would return a kind of pointer to 'obj' plus offset, and even provided
a patch for it (on the ctypes-users lists, maybe even in the ctypes or Python
SF tracker). Unfortunately that was after the feature freeze for Python 2.5.

> Sadly the docs don't seem to be finished :(
> 
>    http://docs.python.org/dev/lib/ctypes-arrays-pointers.html
> 
> 

This problem wouldn't have been described in the docs anyway, but
keep on bugging me about the docs:

Thomas




More information about the Python-list mailing list