On Jul 2, 2008, at 2:00 AM, Dag Sverre Seljebotn wrote:

> Part of my buffer proposal is to provide our own implementation of it
> for Python 2 (I'm unsure about the status for 2.6, it seems like  
> not the
> whole buffer API might be backported). For now I'll just do whatever
> will get us something to play with, but what do people think is a
> long-term solution for this?
>
> What is needed is that for Python 2 is that we bundle something like
> this (psuedo-code):
>
> #ifdef Py2
> PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
>     int flags) {
>
>    if (numpy is available && obj instanceof numpy.ndarray) {
>      view->buf = obj->data;
>      view->strides = obj->strides;
>      view->shape = obj->shape;
>      ...
>    } else if (PIL is available && obj instanceof Imaging.Image) {
>      ...
>    } ... other buffers ...
>
> }
> #endif

That looks good.

> Now the question is, how do I best do this? The "X is  
> available" (and if
> so, #include its headers...) is the tricky part. I'm thinking along  
> the
> lines of having a new special attribute on the classes in question,
> something like this:
>
> cdef extern from "cythonbufferbackwardscompat.h":
>    cdef int NumPyGetBuffer(PyObject*, Py_buffer*, int)
>    cdef int NumPyReleaseBuffer(PyObject*, Py_buffer*)
>
> cdef class numpy.ndarray ... :
>    __cython_py2_getbuffer__ = "NumPyGetBuffer"
>    __cython_py2_releasebuffer__ = "NumPyReleaseBuffer"
>
> And then generate a pyx-file-specific local PyObject_GetBuffer  
> depending
> on the __cython_py2_buffer__ we can find:
>
> #ifdef Py2
> static int PyObject_GetBuffer(PyObject *, Py_buffer *, int);
> #endif
>
> ... code using PyObject_GetBuffer ...
>
> #ifdef Py2
> PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
>    int flags) {
>
>    if (obj is numpy.ndarray) {
>      return NumPyGetBuffer(obj, view, flags);
>    } else if ...
>
>    } else { raise not supported-exception }
>
> }
> #endif
>
>
> Thoughts? A disadvantage is that "cythonbufferbackwardscompat.h": (and
> .c?) must be provided, but inlineable-code-in-pxds can help with  
> that on
> a later date (Robert: This is something I'll push past midterm-eval if
> needed; if so I'll just make it work by hard-coding NumPy-specific  
> stuff
> directly).

Yes, hard coding a NumPy-specific buffer function is fine at this  
point. Inlineable-code-in-pxds should be able to make this much cleaner:

cdef class numpy.ndarray ... :
    cdef inline __cython_py2_getbuffer__(PyObject* self, Py_buffer*  
buf, int k):
         ...
    cdef inline __cython_py2_releasebuffer__(PyObject* self,  
Py_buffer* buf, int k):
         ....

(though those particular names seem overly verbose...why not just  
__getbuffer__ and __releasebuffer__, maybe with a decorator to  
specify py2 only)

- Robert


_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to