cd5853cd3fe8c17a6c63eb21684cced47c7085a8
[harrypotter-wikipedia-cdsw] / win_unicode_console / buffer.py
1
2 from ctypes import (byref, POINTER, Structure, pythonapi,
3         c_int, c_char, c_char_p, c_void_p, py_object, c_ssize_t)
4 import sys
5
6 c_ssize_p = POINTER(c_ssize_t)
7
8 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
9 PyBuffer_Release = pythonapi.PyBuffer_Release
10
11
12 PyBUF_SIMPLE = 0
13 PyBUF_WRITABLE = 1
14
15
16 class Py_buffer(Structure):
17         _fields_ = [
18                 ("buf", c_void_p),
19                 ("obj", py_object),
20                 ("len", c_ssize_t),
21                 ("itemsize", c_ssize_t),
22                 ("readonly", c_int),
23                 ("ndim", c_int),
24                 ("format", c_char_p),
25                 ("shape", c_ssize_p),
26                 ("strides", c_ssize_p),
27                 ("suboffsets", c_ssize_p),
28                 ("internal", c_void_p)
29         ]
30         
31         if sys.version_info[0] < 3:
32                 _fields_.insert(-1, ("smalltable", c_ssize_t * 2))
33         
34         @classmethod
35         def get_from(cls, obj, flags=PyBUF_SIMPLE):
36                 buf = cls()
37                 PyObject_GetBuffer(py_object(obj), byref(buf), flags)
38                 return buf
39         
40         def release(self):
41                 PyBuffer_Release(byref(self))
42
43
44 def get_buffer(obj, writable=False):
45         buf = Py_buffer.get_from(obj, PyBUF_WRITABLE if writable else PyBUF_SIMPLE)
46         try:
47                 buffer_type = c_char * buf.len
48                 return buffer_type.from_address(buf.buf)
49         finally:
50                 buf.release()
51

Benjamin Mako Hill || Want to submit a patch?