3 ms·
In that case I would wrap it with a class to enjoy programming with the reference counted python garbage collector here. from cython.cimports.cpython.mem i
by bb88 4y ago
In that case I would wrap it with a class to enjoy programming with the reference counted python garbage collector here.
from cython.cimports.cpython.mem import PyMem_Malloc, PyMem_Free
@cython.cclass
class SomeMemory:
data: cython.p_double
def __cinit__(self, number: cython.size_t):
# allocate some memory (uninitialised, may contain arbitrary data)
self.data = cython.cast(cython.p_double, PyMem_Malloc(
number * cython.sizeof(cython.double)))
if not self.data:
raise MemoryError()
def __dealloc__(self):
PyMem_Free(self.data) # no-op if self.data is NULL
Extending it into a typical python array type doesn't look that hard. Just need to map the appropriate dunder functions into C array operations. Then optimized functions can directly interact with the C types. Basically any utility function you might need with C data types you would just add to the class.
And at that point, you're back to coding in regular python again.
I hope this helps but good luck with your project no matter which option you take.