Commits

Anonymous committed 99c47d5

carraywrap is PyArray_SimpleNewFromData sample

Comments (0)

Files changed (3)

carraywrap/carraywrapmodule.c

+#include <Python.h>
+#include "structmember.h"
+#include <numpy/arrayobject.h>
+
+typedef struct __CArrayWrap__{
+  PyObject_HEAD
+  char *data, *array;
+  int ndim, *dims, *ptrsize;
+  PyObject *nparray;
+} CArrayWrap;
+
+static void       CArrayWrap_dealloc(CArrayWrap* self);
+static PyObject * CArrayWrap_new(PyTypeObject *type,
+				 PyObject *args, PyObject *kwds);
+static int        CArrayWrap_init(CArrayWrap *self,
+				  PyObject *args, PyObject *kwds);
+
+static void print_indent(int inum)
+{
+  int i;
+  for (i = 0; i < inum; ++i){
+    printf("  ");
+  }
+}
+
+static void print_array_i1d(int *a1d, int *dims, int inum)
+{
+  int i;
+  print_indent(inum);
+  printf("[%d]", dims[0]);
+  for (i = 0; i < dims[0]; ++i){
+    printf(" %d", a1d[i]);
+  }
+  printf("\n");
+}
+
+static void print_array_i2d(int **a2d, int *dims, int inum)
+{
+  int i;
+  print_indent(inum);
+  printf("[%d]\n", dims[0]);
+  for (i = 0; i < dims[0]; ++i){
+    print_array_i1d(a2d[i], dims+1, inum+1);
+  }
+}
+
+static void print_array_i3d(int ***a3d, int *dims, int inum)
+{
+  int i;
+  print_indent(inum);
+  printf("[%d]\n", dims[0]);
+  for (i = 0; i < dims[0]; ++i){
+    print_array_i2d(a3d[i], dims+1, inum+1);
+  }
+}
+
+static PyObject *
+CArrayWrap_print_array(CArrayWrap *self)
+{
+  switch(self->ndim){
+  case 1:
+    print_array_i1d((int *)self->array, self->dims, 0);
+    break;
+  case 2:
+    print_array_i2d((int **)self->array, self->dims, 0);
+    break;
+  case 3:
+    print_array_i3d((int ***)self->array, self->dims, 0);
+    break;
+  }
+
+  return Py_BuildValue("");  /* return None */
+}
+
+static PyMemberDef CArrayWrap_members[] = {
+  {"nparray", T_OBJECT_EX, offsetof(CArrayWrap, nparray), 0, "numpy array"},
+  {NULL}  /* Sentinel */
+};
+
+static PyGetSetDef CArrayWrap_getseters[] = {
+  {NULL}  /* Sentinel */
+};
+
+static PyMethodDef CArrayWrap_methods[] = {
+  {"print_array",
+   (PyCFunction)CArrayWrap_print_array, METH_VARARGS, "print array"},
+  {NULL}  /* Sentinel */
+};
+
+static PyTypeObject CArrayWrapType = {
+    PyObject_HEAD_INIT(NULL)
+    0,				/*ob_size*/
+    "CArrayWrap",	/*tp_name*/
+    sizeof(CArrayWrap),		/*tp_basicsize*/
+    0,				/*tp_itemsize*/
+    (destructor)CArrayWrap_dealloc,	/*tp_dealloc*/
+    0,				/*tp_print*/
+    0,				/*tp_getattr*/
+    0,				/*tp_setattr*/
+    0,				/*tp_compare*/
+    0,				/*tp_repr*/
+    0,				/*tp_as_number*/
+    0,				/*tp_as_sequence*/
+    0,				/*tp_as_mapping*/
+    0,				/*tp_hash */
+    0,				/*tp_call*/
+    0,				/*tp_str*/
+    0,				/*tp_getattro*/
+    0,				/*tp_setattro*/
+    0,				/*tp_as_buffer*/
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,	/*tp_flags*/
+    "CArrayWrap objects",		/* tp_doc */
+    0,				/* tp_traverse */
+    0,				/* tp_clear */
+    0,				/* tp_richcompare */
+    0,				/* tp_weaklistoffset */
+    0,				/* tp_iter */
+    0,				/* tp_iternext */
+    CArrayWrap_methods,		/* tp_methods */
+    CArrayWrap_members,		/* tp_members */
+    CArrayWrap_getseters,		/* tp_getset */
+    0,				/* tp_base */
+    0,				/* tp_dict */
+    0,				/* tp_descr_get */
+    0,				/* tp_descr_set */
+    0,				/* tp_dictoffset */
+    (initproc)CArrayWrap_init,	/* tp_init */
+    0,				/* tp_alloc */
+    CArrayWrap_new,			/* tp_new */
+};
+
+static PyMethodDef module_methods[] = {
+  {NULL}  /* Sentinel */
+};
+
+
+#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
+#define PyMODINIT_FUNC void
+#endif
+PyMODINIT_FUNC
+initcarraywrap(void)
+{
+  PyObject* m;
+  if (PyType_Ready(&CArrayWrapType) < 0){ return; }
+
+  m = Py_InitModule3( "carraywrap", module_methods, "" );
+  if (m == NULL){ return; }
+
+  Py_INCREF(&CArrayWrapType);
+  PyModule_AddObject(m, "CArrayWrap", (PyObject *)&CArrayWrapType);
+  import_array();   /* required NumPy initialization */
+}
+
+
+static void
+CArrayWrap_dealloc(CArrayWrap* self)
+{
+  Py_XDECREF(self->nparray);
+  free(self->dims);
+  free(self->ptrsize);
+  free(self->data);
+  self->ob_type->tp_free((PyObject*)self);
+}
+
+static PyObject *
+CArrayWrap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+  CArrayWrap *self;
+  self = (CArrayWrap *)type->tp_alloc(type, 0);
+  self->ndim = 0;
+  self->ptrsize = NULL;
+  self->dims = NULL;
+  self->nparray = NULL;
+  return (PyObject *)self;
+}
+
+static int
+CArrayWrap_init(CArrayWrap *self, PyObject *args, PyObject *kwds)
+{
+  PyObject *obj;
+  int i, size;
+  char *ptr;
+
+  if (!PyTuple_Check(args)){
+    PyErr_SetString( PyExc_TypeError, "bad arguments");
+    goto fail;
+  }
+  /* alloc self->dims */
+  self->ndim = PyTuple_Size(args);
+  if ((self->dims = malloc(self->ndim*sizeof(int))) == NULL){
+    PyErr_SetString( PyExc_RuntimeError, "malloc for dims fails");
+    goto fail;
+  }
+  if ((self->ptrsize = malloc(self->ndim*sizeof(int))) == NULL){
+    PyErr_SetString( PyExc_RuntimeError, "malloc for ptrsize fails");
+    goto fail;
+  }
+  /* set self->dims */
+  size = 1;
+  for (i = 0; i < self->ndim; ++i){
+    obj = PyTuple_GetItem(args, i);
+    if (!PyInt_Check(obj)){
+      PyErr_Format( PyExc_ValueError, "value(%d) is not int", i);
+      goto fail;
+    }
+    self->dims[i] = PyInt_AsLong(obj);
+    if (self->dims[i] < 0){
+      PyErr_Format( PyExc_ValueError,
+		    "cannot get value(%d) or the value is not positive", i);
+      goto fail;
+    }
+    if (i == 0){
+      self->ptrsize[i] = self->dims[i];
+    }else{
+      self->ptrsize[i] = self->dims[i] * self->ptrsize[i-1];
+    }
+  }
+  /* alloc self->data */
+  self->data = (char *)malloc(self->ptrsize[self->ndim-1]*sizeof(int));
+  if (self->data == NULL){
+    PyErr_SetString( PyExc_RuntimeError, "malloc for data fails");
+    goto fail;
+  }
+  ptr = (char *)&self->array;
+  for (i = 0; i < self->ndim-1; ++i){
+    *((char **)ptr) = (char *)malloc(self->ptrsize[i]*sizeof(char *));
+    ptr = *((char **)ptr);
+    /* if (ptr == NULL){ */
+    /* } */
+  }
+  *(char **)ptr = self->data;
+
+  self->nparray =
+    PyArray_SimpleNewFromData( self->ndim, self->dims, NPY_LONG,
+			       (void *)self->data );
+  if (self->nparray == NULL){
+    PyErr_SetString( PyExc_RuntimeError, "PyArray_SimpleNewFromData fails");
+    goto fail;
+  }
+
+  return 0;
+ fail:
+  free(self->data);
+  free(self->dims);
+  free(self->ptrsize);
+  self->ndim = 0;
+  return -1;
+}

carraywrap/setup.py

+from numpy.distutils.core import setup, Extension
+
+module1 = Extension(
+    'carraywrap',
+    sources = ['carraywrapmodule.c'],
+    extra_compile_args = ["-fPIC"],
+    ## extra_compile_args = ["-fPIC", "-g", "-traceback"],
+)
+
+setup( name = 'my',
+       ext_modules = [module1],
+)
+
+# compile: python setup.py build_ext -i -f

carraywrap/use_caw.py

+from carraywrap import *
+
+caw = CArrayWrap(10,10)
+caw.nparray.fill(0)
+print caw.nparray
+caw.print_array()
+
+caw.nparray.fill(1)
+print caw.nparray
+caw.print_array()