Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

REQ: recipe/docs for creating a buffer-protocol class by wrapping another #3048

Open
jbrockmendel opened this issue Jul 18, 2019 · 1 comment

Comments

@jbrockmendel
Copy link
Contributor

commented Jul 18, 2019

I've got a python-space class that is a thin wrapper around a np.ndarray, and I'd like to make this into a buffer-protocol-compliant cython class so I can pass it to memoryview-expecting cython functions without having to unwrap it every time.

My intuition was that this would look like

cdef Wrapper:
    cdef readonly:
        ndarray _orig

    def __cinit__(self, ndarray orig, *args, **kwargs):
        self._orig = orig

    def __getbuffer__(self, Py_buffer *view, int flags):
        self._orig.__getbuffer__(view, flags)

     def __releasebuffer__(self, Py_buffer *view):
         self._orig.__releasebuffer__(view)

When I do this, I get a compile-time error pointing to self._orig.__releasebuffer__ reading Cannot convert Py_buffer * to Python object which suggests to me that __releasebuffer__ is not in the ndarray c-namespace.

So the request is for a recipe or docs on how to create one memoryview-class that just wraps another.

@TeamSpen210

This comment has been minimized.

Copy link
Contributor

commented Jul 19, 2019

These magic methods are invented by Cython, they're not actually part of the API. What you want to do is call the C-API function PyObject_GetBuffer() on the Numpy array to have it fill in the buffer. You don't need to actually do anything in the release method, since it'll never be called - the array will be saved in the buffer, so it will have the release method called on itself. The function can be cimported from cpython.buffer, and you don't need to return anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.