Skip to content Skip to sidebar Skip to footer

Cython Buffer Declarations For Object Members

I want to have a Cython 'cdef' object with a NumPy member, and be able to use fast buffer access. Ideally, I would do something like: import numpy as np cimport numpy as np cdef

Solution 1:

There is the option to work with memory slices or cython arrays http://docs.cython.org/src/userguide/memoryviews.html

import numpy as np
cimport numpy as np

  cdefclass Model:

    cdefint [:] A

    defsum(self):

        for0 <= i < N:
            s += self.A[i]
        return s

    def__init__(self):
        self.A = np.arange(1000)

Solution 2:

The solution that you are currently using is what I tend to use, i.e. make a local copy in the function. It's not elegant, but I don't think you take a huge performance hit (or at least in my case, I'm doing a lot of work in the method, so it doesn't make a discernible difference). I've also created a C-array in the __cinit__ method and then filled it with the data in __init__ (make sure you use __dealloc__ to clean-up properly). You lose some of the features of the numpy array, but you can still use it as you would a c-array.

You might also check out the discussion in this older email on the cython list:

http://codespeak.net/pipermail/cython-dev/2009-April/005214.html

Post a Comment for "Cython Buffer Declarations For Object Members"