[Numpy-discussion] numpy C++ swig class example
Bill Spotz
wfspotz at sandia.gov
Wed Jun 10 14:52:22 EDT 2009
Jared,
Typically, public data members would be handled in SWIG with, I
believe, the "out" typemap. numpy.i does not support this typemap
because there is no general way that I know of to tell it that, for
example, _nrow and _ncol are the dimensions of data.
Faced with this problem, and a desire to have a "data" attribute, I
would probably do the following (ignoring the fact that the
constructor has an argument named "data" that clashes with the public
variable):
%ignore Array2D::data;
%apply (int DIM1, int DIM2, double* IN_ARRAY2) {(int nrow, int ncol,
double *data)};
%include "Array2D.h"
%extend(Array2D)
{
PyObject * _getData()
{
npy_intp dims[2] = {self->_nrow, self->_ncol};
return PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, (void*)data);
}
}
%pythoncode
%{
data = property(_getData, doc="docstring for data")
%}
You'll want four spaces as indentation within the %pythoncode
directive to ensure it fits properly under the Array2D python proxy
class. This should allow getting the entire array and setting and
getting elements of the array:
>>> a = Array2D([[1,2],[3,4]])
>>> a.data[0,0] = 5
>>> print a.data
[[5 2]
[3 4]]
>>> print a.data[1,1]
4
I don't think I would do this for an a class that advertises itself as
an array (for this case, I would make sure that an instance of Array2D
behaves like an array rather than its "data" attribute), but I could
see other classes that might have an attribute that is an array, where
you would want to do it.
On Jun 9, 2009, at 10:52 PM, Rubin, Jared wrote:
> I am using the numpy.i interface file and have gotten the cookbook/
> swig example to work from scipy.
> Are there any examples of appyling the numpy.i to a C++ header file.
> I would like to generate a lightweight
> Array2D class that just uses doubles and would have the following
> header file
>
> Array2D.h
> =========
> class Array2D {
> public:
> int _nrow;
> int _ncol;
> double* data;
> Array2DD(int nrow, int ncol, double *data);
> }
>
> // I would expect the have the following Array2D.i interface file
> %module array2DD
>
> %{
> #define SWIG_FILE_WITH_INIT
> #include "Array2D.h"
> %}
>
> %include "numpy.i"
>
> %init %{
> import_array();
> %}
>
> %ignore Array2D();
> %ignore Array2D(long nrow, long ncol);
> %apply (int DIM1, int DIM2, double* IN_ARRAY2) {(int nrow, int ncol,
> double *data)}
> %include "Array2D.h"
>
** Bill Spotz **
** Sandia National Laboratories Voice: (505)845-0170 **
** P.O. Box 5800 Fax: (505)284-0154 **
** Albuquerque, NM 87185-0370 Email: wfspotz at sandia.gov **
More information about the NumPy-Discussion
mailing list