| 1 |
# |
| 2 |
# distutils: language = c++ |
| 3 |
# |
| 4 |
|
| 5 |
# Compatible with Python >= 2.6, Cython |
| 6 |
# Not PYPY apparently |
| 7 |
|
| 8 |
from libc.stdlib cimport malloc, free |
| 9 |
|
| 10 |
from mpi4py import MPI |
| 11 |
|
| 12 |
########################################################### |
| 13 |
|
| 14 |
cdef dict TypeDict = { |
| 15 |
"?" : MPI.C_BOOL, |
| 16 |
"c" : MPI.CHAR, |
| 17 |
"b" : MPI.SIGNED_CHAR, |
| 18 |
"h" : MPI.SHORT, |
| 19 |
"i" : MPI.INT, |
| 20 |
"l" : MPI.LONG, |
| 21 |
"q" : MPI.LONG_LONG, |
| 22 |
"p" : MPI.AINT, |
| 23 |
"B" : MPI.UNSIGNED_CHAR, |
| 24 |
"H" : MPI.UNSIGNED_SHORT, |
| 25 |
"I" : MPI.UNSIGNED, |
| 26 |
"L" : MPI.UNSIGNED_LONG, |
| 27 |
"Q" : MPI.UNSIGNED_LONG_LONG, |
| 28 |
"f" : MPI.FLOAT, |
| 29 |
"d" : MPI.DOUBLE, |
| 30 |
"g" : MPI.LONG_DOUBLE, |
| 31 |
"Zf": MPI.C_FLOAT_COMPLEX, |
| 32 |
"Zd": MPI.C_DOUBLE_COMPLEX, |
| 33 |
"Zg": MPI.C_LONG_DOUBLE_COMPLEX, |
| 34 |
"F" : MPI.C_FLOAT_COMPLEX, |
| 35 |
"D" : MPI.C_DOUBLE_COMPLEX, |
| 36 |
"G" : MPI.C_LONG_DOUBLE_COMPLEX, |
| 37 |
} |
| 38 |
|
| 39 |
cdef object getformat(Py_buffer* pybuf): |
| 40 |
cdef object obj = <object> pybuf.obj |
| 41 |
|
| 42 |
# numpy.ndarray |
| 43 |
try: return obj.dtype.char |
| 44 |
except (AttributeError, TypeError): pass |
| 45 |
|
| 46 |
# array.array |
| 47 |
try: return obj.typecode |
| 48 |
except (AttributeError, TypeError): pass |
| 49 |
|
| 50 |
if pybuf.format is NULL: return "B" |
| 51 |
return PyUnicodeString_FromString(pybuf.format) |
| 52 |
|
| 53 |
cdef int bufflags = PyBUF_ANY_CONTIGUOUS | PyBUF_WRITABLE | PyBUF_FORMAT |
| 54 |
|
| 55 |
cdef class Buffer(object): |
| 56 |
def __cinit__(self, object data): |
| 57 |
if not PyObject_CheckBuffer(data): |
| 58 |
raise TypeError("object does not present buffer interface") |
| 59 |
|
| 60 |
cdef Py_buffer* pybuf = &self.pybuf |
| 61 |
PyObject_GetBuffer(data, pybuf, bufflags) |
| 62 |
self.dtype = TypeDict[getformat(pybuf)] |
| 63 |
self.items = pybuf.len // pybuf.itemsize |
| 64 |
|
| 65 |
def __dealloc__(self): |
| 66 |
PyBuffer_Release(&self.pybuf) |