-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This builds up a basic char array object in C with some Python trappings for handling construction and cleanup of the object. Otherwise provides no interface for accessing this object in Python. Since it's purpose is merely to manage a block of memory requested by the user to be passed off and used by other objects that implement the buffer protocol, there is no need for it to have other functionality. It simply allocates memory from Python's memory allocator and frees it on cleanup. Implements the buffer protocol in Cython for this object. Thus allowing the memory allocated to be reused by NumPy arrays or other Python objects that support the buffer protocol.
- Loading branch information
Showing
2 changed files
with
134 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,43 @@ | ||
cimport cpython | ||
cimport cpython.mem | ||
from cpython.mem cimport PyMem_Malloc, PyMem_Free | ||
|
||
cimport pysharedmem | ||
|
||
include "version.pxi" | ||
|
||
|
||
cdef class cbuffer: | ||
cdef char[:] buf | ||
|
||
def __cinit__(self, Py_ssize_t length): | ||
self.buf = None | ||
|
||
if length <= 0: | ||
raise ValueError("length must be positive definite") | ||
|
||
cdef void* ptr = PyMem_Malloc(length * sizeof(char)) | ||
if not ptr: | ||
raise MemoryError("unable to allocate buffer") | ||
|
||
self.buf = <char[:length]>ptr | ||
|
||
def __getbuffer__(self, Py_buffer *buffer, int flags): | ||
buffer.buf = &self.buf[0] | ||
buffer.obj = self | ||
buffer.len = len(self.buf) | ||
buffer.readonly = 0 | ||
buffer.itemsize = self.buf.ndim | ||
buffer.format = "c" | ||
buffer.ndim = self.buf.ndim | ||
buffer.shape = self.buf.shape | ||
buffer.strides = self.buf.strides | ||
buffer.suboffsets = NULL | ||
buffer.internal = NULL | ||
|
||
def __releasebuffer__(self, Py_buffer *buffer): | ||
pass | ||
|
||
def __dealloc__(self): | ||
PyMem_Free(&self.buf[0]) | ||
self.buf = None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters