2 from ctypes import (byref, POINTER, Structure, pythonapi,
3 c_int, c_char, c_char_p, c_void_p, py_object, c_ssize_t)
6 c_ssize_p = POINTER(c_ssize_t)
8 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
9 PyBuffer_Release = pythonapi.PyBuffer_Release
16 class Py_buffer(Structure):
21 ("itemsize", c_ssize_t),
26 ("strides", c_ssize_p),
27 ("suboffsets", c_ssize_p),
28 ("internal", c_void_p)
31 if sys.version_info[0] < 3:
32 _fields_.insert(-1, ("smalltable", c_ssize_t * 2))
35 def get_from(cls, obj, flags=PyBUF_SIMPLE):
37 PyObject_GetBuffer(py_object(obj), byref(buf), flags)
41 PyBuffer_Release(byref(self))
44 def get_buffer(obj, writable=False):
45 buf = Py_buffer.get_from(obj, PyBUF_WRITABLE if writable else PyBUF_SIMPLE)
47 buffer_type = c_char * buf.len
48 return buffer_type.from_address(buf.buf)