Skip to content

Commit 5909cac

Browse files
committed
add pickling support for MKLMemory
1 parent 72737f8 commit 5909cac

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

mkl/_mkl_memory.pyx

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,29 @@ cdef extern from "stdatomic.h" nogil:
4242
int atomic_load(atomic_int *obj)
4343

4444

45+
def _mkl_memory_from_bytes(bytes data, Py_ssize_t alignment):
46+
cdef Py_ssize_t nbytes = len(data)
47+
cdef MKLMemory mem = MKLMemory(nbytes, alignment=alignment)
48+
49+
cdef void *dst = mem._memory_ptr
50+
cdef char *src = data
51+
52+
with nogil:
53+
memcpy(dst, src, nbytes)
54+
55+
return mem
56+
57+
4558
cdef class MKLMemory:
4659
cdef void *_memory_ptr
4760
cdef Py_ssize_t nbytes
61+
cdef Py_ssize_t alignment
4862
cdef atomic_int exported_buffers
4963

5064
cdef _cinit_empty(self):
5165
self._memory_ptr = NULL
5266
self.nbytes = 0
67+
self.alignment = 0
5368
atomic_init(&self.exported_buffers, 0)
5469

5570
cdef _cinit_malloc(self, Py_ssize_t nbytes, Py_ssize_t alignment):
@@ -62,6 +77,7 @@ cdef class MKLMemory:
6277
if (p):
6378
self._memory_ptr = p
6479
self.nbytes = nbytes
80+
self.alignment = alignment
6581
else:
6682
raise MemoryError(
6783
"MKL memory allocation failed."
@@ -81,6 +97,7 @@ cdef class MKLMemory:
8197
if (p):
8298
self._memory_ptr = p
8399
self.nbytes = num * size
100+
self.alignment = alignment
84101
else:
85102
raise MemoryError(
86103
"MKL memory allocation failed."
@@ -176,6 +193,10 @@ cdef class MKLMemory:
176193
self._memory_ptr = p
177194
self.nbytes = new_nbytes
178195

196+
def tobytes(self):
197+
cdef char* data_ptr = <char*>self._memory_ptr
198+
return data_ptr[:self.nbytes]
199+
179200
@property
180201
def nbytes(self):
181202
return self.nbytes
@@ -184,6 +205,10 @@ cdef class MKLMemory:
184205
def size(self):
185206
return self.nbytes
186207

208+
@property
209+
def alignment(self):
210+
return self.alignment
211+
187212
@property
188213
def _pointer(self):
189214
return <size_t>(self._memory_ptr)
@@ -199,3 +224,6 @@ cdef class MKLMemory:
199224

200225
def __sizeof__(self):
201226
return self.nbytes
227+
228+
def __reduce__(self):
229+
return (_mkl_memory_from_bytes, (self.tobytes(), self.alignment))

0 commit comments

Comments
 (0)