From: Edward Srouji <edwards@xxxxxxxxxxxx> Add new MemAlloc class which wraps some C memory allocation functions such as aligned_alloc, malloc and free. This allows Pyverbs' users to easily allocate and free memory in C style, i.e when the memory address must be passed to a driver API. Signed-off-by: Edward Srouji <edwards@xxxxxxxxxxxx> Reviewd-by: Daria Velikovsky <daria@xxxxxxxxxxxx> Reviewd-by: Noa Osherovich <noaos@xxxxxxxxxxxx> --- pyverbs/base.pxd | 3 +++ pyverbs/base.pyx | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/pyverbs/base.pxd b/pyverbs/base.pxd index e85f7c020e1c..e956a79915ff 100644 --- a/pyverbs/base.pxd +++ b/pyverbs/base.pxd @@ -9,3 +9,6 @@ cdef class PyverbsObject(object): cdef class PyverbsCM(PyverbsObject): cpdef close(self) + +cdef class MemAlloc(object): + pass diff --git a/pyverbs/base.pyx b/pyverbs/base.pyx index 8b3e6741ae19..a41cfc748ad0 100644 --- a/pyverbs/base.pyx +++ b/pyverbs/base.pyx @@ -3,8 +3,14 @@ import logging from pyverbs.pyverbs_error import PyverbsRDMAError +from libc.stdlib cimport malloc, free +from libc.stdint cimport uintptr_t from libc.errno cimport errno +cdef extern from 'stdlib.h': + void *aligned_alloc(size_t alignment, size_t size) + + cpdef PyverbsRDMAErrno(str msg): return PyverbsRDMAError(msg, errno) @@ -58,3 +64,23 @@ cdef class PyverbsCM(PyverbsObject): cpdef close(self): pass + + +cdef class MemAlloc(object): + @staticmethod + def malloc(size): + ptr = malloc(size) + if not ptr: + raise MemoryError('Failed to allocate memory') + return <uintptr_t>ptr + + @staticmethod + def aligned_alloc(size, alignment=8): + ptr = aligned_alloc(alignment, size) + if not ptr: + raise MemoryError('Failed to allocate memory') + return <uintptr_t>ptr + + @staticmethod + def free(ptr): + free(<void*><uintptr_t>ptr) -- 2.21.0