Providing array interface from SWIG-wrapped C struct

Michele Vallisneri vallis at
Thu Oct 12 12:41:37 CDT 2006

Does anybody here have experience about offering the array interface  
from a SWIG-wrapped C struct?

I have tried the following, borrowing code from numpy's arrayobject.c:

%extend real_vec_t {
   PyObject *__array_struct__() {
     /* From numpy/arrayobject.c/array_struct_get */

     PyArrayInterface *inter;

     inter = (PyArrayInterface *)_pya_malloc(sizeof(PyArrayInterface));

     inter->two = 2;
     inter->nd = 1;
     inter->typekind = 'f';
     inter->itemsize = sizeof(float);
     inter->flags = (NPY_CONTIGUOUS | NPY_OWNDATA | NPY_ALIGNED |  

     inter->shape = (intp *)_pya_malloc(2*sizeof(intp));
     inter->strides = inter->shape + 1;
     *(inter->shape) = self->n;
     *(inter->strides) = 1;

     inter->data = (void *)(self->d);
     inter->descr = 0;
     return PyCObject_FromVoidPtr(inter,0);

When passing such a SWIG real_vec_t object to numpy.array, numpy gets  
a PyArrayInterface that fails to check correctly as a Python C  
object. Three comments:

- The original numpy/arrayobject.c code actually gets its return  
value from PyCObject_FromVoidPtrAndDesc(inter,self,...); but in this  
context self does not point to a PyObject, but rather to the C  
struct, so I don't think I can use that form.

- The code above does not deal with properly destructing the  
PyArrayInterface, setting refcounts, etc. But I was going to worry  
about those later.

- My problem is probably with SWIG rather than numpy... but I thought  
the people in this forum (rather than those at the SWIG forum) would  
be most likely to have encountered a situation similar to these.

Thanks a lot for any help, or just for reading this post.


Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo

More information about the Numpy-discussion mailing list