ctypes and buffers

Thomas Jollans thomas at jollybox.de
Sun Sep 19 14:10:39 CEST 2010


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!

 * 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.

> 
> It works, but is there a standard way to do this in ctypes?  I
> couldn't find anything in the documentation.  Python 2.6 for now.
> Thanks.
> 
> 
> Carl Banks



More information about the Python-list mailing list