[Numpy-discussion] More help with numpy and SWIG

vallis.35530053 at bloglines.com vallis.35530053 at bloglines.com
Tue May 22 22:18:25 EDT 2007


Hello,

I am trying to use numpy in conjuction with a custom SWIGged C struct
(real_vec_t) that contains array data. I'd like to use the array interface
to share the array data between real_vec_t and numpy. I have two questions
for a combined numpy/SWIG magician:

- This is how I implement the array
interface in real_vec_t, so that if rvt is a real_vec_t instance, I can do
na = numpy.array(rvt) and get a numpy array with the same content. I define
the python attribute,

%extend real_vec_t {
%pythoncode %{
__array_struct__
= property(get_array_struct,doc='Array protocol')
%}
[...]
%}

which
calls the C function (thanks to Lisandro Dalcin for suggesting this)

%extend
real_vec_t {
  PyObject *get_array_struct() {
    [...create the PyArrayInterface
pointed to by "inter"...]
  
    [...do Py_INCREF(self) (see below)...]


    [...return PyCObject pointing to inter (see below)...]
  }
%}

I have problems with the last two steps. I'm supposed to do a Py_INCREF on
the SWIG object so that the array data is preserved until all numpy arrays
that may come to use it are destroyed. But I don't think it's correct to say
"Py_INCREF(self)", because in this context self is a pointer to a real_vec_t
structure, not the SWIG PyObject that wraps it... how should I call Py_INCREF?


I have a related problem for the last step. I'm supposed to return PyCObject_FromVoidPtrAndDesc(inter,self,inter_free),
where inter is the pointer to the PyArrayInterface, inter_free points to a
function that will free any memory allocated with the PyArrayInterface, and
self, again, should be a pointer to the SWIG wrapper, not just the real_vec_t
C struct.

- The second question is about the conditions under which the
data pointed to by PyArrayInterface is shared with the numpy array I create
with numpy.array(rvt), or it is copied. Is this a function of the flags I
set in PyArrayInterface, of flags that must be passed to numpy.array(), or
both? I couldn't quite dig this out of the numpy manual (but will happily
take a pointer to the discussion therein...)




More information about the NumPy-Discussion mailing list