numpy and extending python with c

Greg Landrum drgergl at mindspring.com
Fri Jan 11 11:44:03 EST 2002


"les ander" <les_ander at yahoo.com> wrote in message
news:a2972632.0201091527.4d5300cc at posting.google.com...
> Hi,
> i have a c program that takes in a square matrix
> and and returns another one of the same size. However
> i do not know how to pass the numpy matrix to a c program
> and get one back. can some one please give me a simple example.
> thanks

Here are a couple lines demonstrating how to pass a Numeric matrix from C ->
Python:
    PyArrayObject *res = (PyArrayObject
*)PyArray_FromDims(2,dims,PyArray_INT);
    // iRes is a dims[0] x dims[1] array of ints
    memcpy((void *)(res->data),(void *)(iRes),dims[0]*dims[1]*sizeof(int));
    return(res);

To use a Numeric matrix from Python in your C code, you can use something
like this:
  PyArrayObject *resultsContig;
  PyObject *resultsArray;
  double *cArray;
  int arraySize;
  if (!PyArg_ParseTuple(args, "O!",&PyArray_Type, &resultsArray))
    return NULL;
  if(((PyArrayObject *)resultsArray)->descr->type_num == PyArray_DOUBLE ||
     ((PyArrayObject *)resultsArray)->descr->type_num == PyArray_FLOAT){
    resultsContig = (PyArrayObject
*)PyArray_ContiguousFromObjec(resultsArray,PyArray_DOUBLE,1,1);
    cArray = (double *)resultsContig->data;
    arraySize = resultsContig->dimensions[0];
  } else {
   // it's a bad array, deal with it.
  }

I hope this helps,
-greg





More information about the Python-list mailing list