Basic numpy testcase working
authorDag Sverre Seljebotn <dagss@student.matnat.uio.no>
Sat, 2 Aug 2008 09:20:35 +0000 (11:20 +0200)
committerDag Sverre Seljebotn <dagss@student.matnat.uio.no>
Sat, 2 Aug 2008 09:20:35 +0000 (11:20 +0200)
Cython/Includes/numpy.pxd
tests/run/tnumpy.pyx [new file with mode: 0644]

index 5965b1e6c350636c8b3e96c03f755ed0830f7b5d..e09fc05d270d104743ab3659b8253c486aa2c179 100644 (file)
@@ -2,23 +2,39 @@ cdef extern from "Python.h":
     ctypedef int Py_intptr_t
     
 cdef extern from "numpy/arrayobject.h":
-    ctypedef void PyArrayObject
-    int PyArray_TYPE(PyObject* arr)
-    
+    ctypedef Py_intptr_t npy_intp
+    ctypedef struct PyArray_Descr:
+        int elsize
+
     ctypedef class numpy.ndarray [object PyArrayObject]:
         cdef:
             char *data
             int nd
-            Py_intptr_t *dimensions
-            Py_intptr_t *strides
+            npy_intp *dimensions 
+            npy_intp *strides
             object base
             # descr not implemented yet here...
             int flags
             int itemsize
             object weakreflist
+            PyArray_Descr* descr
+
+        def __getbuffer__(ndarray self, Py_buffer* info, int flags):
+            if sizeof(npy_intp) != sizeof(Py_ssize_t):
+                raise RuntimeError("Py_intptr_t and Py_ssize_t differs in size, numpy.pxd does not support this")
 
-        def __getbuffer__(self, Py_buffer* info, int flags):
             cdef int typenum = PyArray_TYPE(self)
+            
+            info.buf = <void*>self.data
+            info.ndim = 2
+            info.strides = <Py_ssize_t*>self.strides
+            info.shape = <Py_ssize_t*>self.dimensions
+            info.suboffsets = NULL
+            info.format = "i"
+            info.itemsize = self.descr.elsize
+            info.readonly = not PyArray_ISWRITEABLE(self)
+
+            # PS TODO TODO!: Py_ssize_t vs Py_intptr_t
 
             
 ##   PyArrayObject *arr = (PyArrayObject*)obj;
@@ -58,7 +74,8 @@ cdef extern from "numpy/arrayobject.h":
 ##             print "hello" + str(43) + "asdf" + "three"
 ##             pass
 
-
+    cdef int PyArray_TYPE(ndarray arr)
+    cdef int PyArray_ISWRITEABLE(ndarray arr)
 
     ctypedef unsigned int npy_uint8
     ctypedef unsigned int npy_uint16
diff --git a/tests/run/tnumpy.pyx b/tests/run/tnumpy.pyx
new file mode 100644 (file)
index 0000000..a418cf2
--- /dev/null
@@ -0,0 +1,22 @@
+# cannot be named "numpy" in order to no clash with the numpy module!
+
+cimport numpy
+
+try:
+    import numpy
+    __doc__ = """
+
+    >>> basic()
+    [[0 1 2 3 4]
+     [5 6 7 8 9]]
+    2 0 9 5
+
+
+"""
+except:
+    __doc__ = ""
+
+def basic():
+    cdef object[int, 2] buf = numpy.arange(10).reshape((2, 5))
+    print buf
+    print buf[0, 2], buf[0, 0], buf[1, 4], buf[1, 0]