Commits

Anonymous committed 69db5bb

MyArray_AsCArray for debug

  • Participants
  • Parent commits 01f878a

Comments (0)

Files changed (1)

ascarray/ascarraymodule.c

   }
 }
 
+static int
+MyArray_AsCArray(PyObject **op, void *ptr, int *dims, int nd,
+                 PyArray_Descr* typedescr)
+{
+    PyArrayObject *ap;
+    int n, m, i, j;
+    char **ptr2;
+    char ***ptr3;
+
+    if ((nd < 1) || (nd > 3)) {
+        PyErr_SetString(PyExc_ValueError,
+                        "C arrays of only 1-3 dimensions available");
+        Py_XDECREF(typedescr);
+        return -1;
+    }
+    if ((ap = (PyArrayObject*)PyArray_FromAny(*op, typedescr, nd, nd,
+                                              NPY_CARRAY, NULL)) == NULL)
+        return -1;
+    switch(nd) {
+    case 1:
+        *((char **)ptr) = ap->data;
+        break;
+    case 2:
+        n = ap->dimensions[0];
+        ptr2 = (char **)malloc(n * sizeof(char *));
+        if (!ptr2) goto fail;
+        for (i=0; i<n; i++) {
+            ptr2[i] = ap->data + i*ap->strides[0];
+        }
+        *((char ***)ptr) = ptr2;
+        break;
+    case 3:
+        n = ap->dimensions[0];
+        m = ap->dimensions[1];
+        ptr3 = (char ***)malloc(n*(m+2) * sizeof(char *));
+        if (!ptr3) goto fail;
+        for (i=0; i<n; i++) {
+	  /* ptr3[i] = ptr3[n + m*i]; */
+	    ptr3[i] = ptr3[n + (m-1)*i];
+            for (j=0; j<m; j++) {
+                ptr3[i][j] = ap->data + i*ap->strides[0] + \
+                    j*ap->strides[1];
+            }
+        }
+        *((char ****)ptr) = ptr3;
+    }
+    memcpy(dims, ap->dimensions, nd*sizeof(int));
+    *op = (PyObject *)ap;
+    return 0;
+
+ fail:
+    PyErr_SetString(PyExc_MemoryError, "no memory");
+    return -1;
+}
+
 static PyObject *
 print_array(PyObject *dummy, PyObject *args)
 {
   case 3:
     if (PyArray_ISFLOAT(o1)){
       double ***ptr;
-      PyObject *tmp=o1;
-      Py_INCREF(tmp);
-      PyArray_AsCArray(&o1, (void *)&ptr, dims, nd, NULL);
+      MyArray_AsCArray(&o1, (void *)&ptr, dims, nd, NULL);
       print_array_d3d(ptr, dims[0], dims[1], dims[2], 0);
       PyArray_Free(o1, (void *)ptr);
-      Py_DECREF(tmp);
     }else if (PyArray_ISINTEGER(o1)){
       return NULL;
     }else{