[Numpy-discussion] swig numpy2carray converters

Georg Holzmann grh@mur...
Wed Nov 21 11:07:58 CST 2007


Hallo!

As chris said, I need to make an example:
http://grh.mur.at/software/numpy2carray.tar.gz

I added the following class-example:
class_example.h: the C++ code
class_example.i: the SWIG interface file
class_example_usage.py: example usage in python


And some comments:

Bill Spotz schrieb:
> Here is what I am proposing you do: in your interface file, add 
> something like
> 
>     PyObject * getMatrix()
>     {
>         npy_intp dims[2] = { /* Obtain the dimensions to your internal 
> matrix */ };
>         double * data = /* Obtain the pointer to you internal matrix */;
>         return PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, (void*)data);
>     }
> 
> For your function, use the INPLACE_ARRAY2 typemap:
> 
>     %apply (double* INPLACE_ARRAY2, int DIM1, int DIM2) {(double* 
> matrix, int rows, int cols)};
>     void myFunction(double* matrix, int rows, int cols, double 
> parameter, ...);
> 
> And then in python you can do this:
> 
>     m = getMatrix()
>     myFunction(m, 3.14, ...)

I see ... but what I mean with output of a matrix without copy is 
actually only your getMatrix() funtion I guess - this is basically what 
getBigData() does in class_example.h together with class_example.i.

BTW: what is the difference between PyArray_SimpleNewFromData() and 
PyArray_FromDimsAndData() ?
(I don't have this book ...)

>> Again I do not see the problem - see e.g. ARRAY2_OUT_COPY in 
>> numpy2carray.i, shouldn't this be the same ?
> 
> I do not understand the use case for which that typemap works.  You 
> create "ttype t1", then pass its address to the function as the pointer 
> to the data.  This has to be useless to the function.  After the 
> function returns, you access this pointer as if it points to meaningful 
> data.  How is this possible?  The address of t1 isn't going to change, 
> and only a single element is allocated.

See also the class_example_usage.py - there I used the ARRAY2_OUT_COPY 
for the getBigDataCopy() method.

LG
Georg


More information about the Numpy-discussion mailing list