ctypes and buffers

Carl Banks pavlovevidence at gmail.com
Mon Sep 20 00:35:43 CEST 2010


On Sep 19, 5:10 am, Thomas Jollans <tho... at jollybox.de> wrote:
> On Sunday 19 September 2010, it occurred to Carl Banks to exclaim:
> > I am creating a ctypes buffer from an existing non-ctypes object that
> > supports buffer protocol using the following code:
>
> > from ctypes import *
>
> > PyObject_AsReadBuffer = pythonapi.PyObject_AsReadBuffer
> > PyObject_AsReadBuffer.argtypes =
> > [py_object,POINTER(c_void_p),POINTER(c_size_t)]
> > PyObject_AsReadBuffer.restype = None
>
> > def ctypes_buffer_from_buffer(buf):
> >     cbuf = c_void_p()
> >     size = c_size_t()
> >     PyObject_AsReadBuffer(buf,byref(cbuf),byref(size))
> >     return cbuf
>
> If I understand what you are doing correctly, you're referencing a Python
> buffer object and returning a pointer wrapped in some ctypes thingy. hmm. I
> see some problems in your code:
>
>  * You're not passing the size along. In the name of sanity, why on earth
>    not?! The pointer cannot be safely used without knowing how long the area
>    of memory referenced is!

How D'Olivero of you to overreact this way.

A. No, and
B. I already know the size of the object


>  * You're using the old buffer protocol. You might rather implement this with
>    the one introduced with Python 3.0, and supported in 2.6 as well.

Hmm, I didn't know they got that into 2.6.  Maybe I'll do that,
thanks.


Carl Banks



More information about the Python-list mailing list