[Numpy-discussion] PyArray_AsCArray (cfunction, in Array API) in Numpy User Guide

Takafumi Arakaki aka.tkf@gmail....
Mon Sep 21 02:07:02 CDT 2009


Hi,

I wrote sample code and it works fine.
This is my code, in case anyone else want to know how to use it:

#include <Python.h>
#include "structmember.h"
#include <numpy/arrayobject.h>

static PyObject *
print_a1(PyObject *dummy, PyObject *args)
{
  npy_intp dims[3]; /* PyArray_AsCArray is for ndim <= 3 */
  int typenum;
  int i, nd;
  PyObject *o1;
  double *d1;
  PyArray_Descr *descr;

  if (PyArg_ParseTuple(args, "O:print_a1", &o1) < 0) {
    PyErr_SetString( PyExc_TypeError,  "bad arguments");
    return NULL;
  }

  nd = PyArray_NDIM(o1);
  typenum = NPY_DOUBLE;
  descr = PyArray_DescrFromType(typenum);
  if (PyArray_AsCArray(&o1, (void *)&d1, dims, nd, descr) < 0){
    PyErr_SetString( PyExc_TypeError,  "error on getting c array");
    return NULL;
  }

  printf("[%d] ", dims[0]);
  for (i = 0; i < dims[0]; ++i){
    printf("%.2f ", d1[i]);
  }
  printf("\n");

  printf("if ( ((PyArrayObject *)o1)->data == d1): ");
  if ( ((PyArrayObject *)o1)->data == (char *)d1){
    printf("True\n");
  }else{
    printf("False\n");
  }

  if (PyArray_Free(o1, (void *)&d1) < 0){
    PyErr_SetString( PyExc_TypeError,  "PyArray_Free fail");
    return NULL;
  }

  return Py_BuildValue("");  /* return None */
}


static PyMethodDef module_methods[] = {
  {"print_a1", (PyCFunction)print_a1, METH_VARARGS, ""},
  {NULL}  /* Sentinel */
};

#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initaca(void)
{
  (void) Py_InitModule("aca", module_methods);
  import_array();   /* required NumPy initialization */
}


Thanks,
Takafumi


More information about the NumPy-Discussion mailing list