Pass the numpy.ndarray to c extension
Thank for Dave Abrahams's suggestion to "numpy.ndarray did not match PyArrayObject *" problem. I didn't use the lvalue converter before. I will look up how to do it. Since what I really want to do is to pass the numpy.ndarray to c extension, so I started a new title. I find a way to pass the argument from the webpage: http://numpy.scipy.org/numpydoc/numpy-13.html . It uses PyArg_ParseTuple to transfer PyObject into PyArrayObject. I implemented two functions with PyArg_ParseTuple(), but they all reported error. /***************c extension*********/ void testArray(PyObject * args) { PyObject *input; PyArrayObject *array; if (!PyArg_ParseTuple(args, "O", &input)) printf("getting input failed!\n"); else printf("getting input sucess!\n"); array = (PyArrayObject *) PyArray_ContiguousFromObject(input, PyArray_INT, 0, 3); if (array == NULL) printf("getting array failed!\n"); else printf("getting array sucess!\n"); } static PyObject * trace(PyObject *self, PyObject *args) { PyObject *input; PyArrayObject *array; double sum; int i, n; if (!PyArg_ParseTuple(args, "O", &input)) return NULL; array = (PyArrayObject *) PyArray_ContiguousFromObject(input, PyArray_DOUBLE, 2, 2); if (array == NULL) return NULL; n = array->dimensions[0]; if (n > array->dimensions[1]) n = array->dimensions[1]; sum = 0.; for (i = 0; i < n; i++) sum += *(double *)(array->data + i*array->strides[0] + i*array->strides[1]); Py_DECREF(array); return PyFloat_FromDouble(sum); } /************error report************/
import hello import numpy c = numpy.arange(25).reshape((5,5)) print c [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] b = hello.trace(c,c) b SystemError: new style getargs format but argument is not a tuple d = hello.testArray(c); getting input failed! d SystemError: new style getargs format but argument is not a tuple
-- Qinfeng(Javen) Shi Research School of Information Sciences and Engineering Australian National University Locked Bag 8001 Canberra ACT 2601
participants (1)
-
Qinfeng(Javen) Shi