[Numpy-discussion] SWIG and numpy.i

Bill Spotz wfspotz@sandia....
Tue Mar 24 12:13:35 CDT 2009


Kevin,

You need to declare vecSum() *after* you %include "numpy.i" and use  
the %apply directive.  Based on what you have, I think you can just  
get rid of the "extern double vecSum(...)".  I don't see what purpose  
it serves.  As is, it is telling swig to wrap vecSum() before you have  
set up your numpy typemaps.

On Mar 24, 2009, at 10:33 AM, Kevin Françoisse wrote:

> Hi everyone,
>
> I have been using NumPy for a couple of month now, as part of my  
> research project at the university.  But now, I have to use a big C  
> library I wrote myself in a python project.  So I choose to use SWIG  
> for the interface between both my python script and my C library. To  
> make things more comprehensible, I wrote a small C methods that  
> illustrate my problem:
>
> /* matrix.c */
>
> #include <stdlib.h>
> #include <stdio.h>
> /* Compute the sum of a vector of reals */
> double vecSum(int* vec,int m){
>    int  i;
>    double sum =0.0;
>
>    for(i=0;i<m;i++){
>        sum += vec[i];
>    }
>    return sum;
> }
>
> /***/
>
> /* matrix.h */
>
> double vecSum(int* vec,int m);
>
> /***/
>
> /* matrix.i */
>
> %module matrix
> %{
> #define SWIG_FILE_WITH_INIT
> #include "matrix.h"
> %}
>
> extern double vecSum(int* vec, int m);
>
> %include "numpy.i"
>
> %init %{
> import_array();
> %}
>
> %apply (int* IN_ARRAY1, int DIM1) {(int* vec, int m)};
> %include "matrix.h"
>
> /***/
>
> I'm using a python script to compile my swig interface and my C  
> files (running Mac OS X 10.5)
>
> /* matrixSetup.py */
>
> from distutils.core import setup, Extension
> import numpy
>
> setup(name='matrix', version='1.0', ext_modules  
> =[Extension('_matrix', ['matrix.c','matrix.i'],
>     include_dirs = [numpy.get_include(),'.'])])
>
> /***/
>
> Everything seems to work fine ! But when I test my wrapped module in  
> python with an small NumPy array, here what I get :
>
> >>> import matrix
> >>> from numpy import *
> >>> a = arange(10)
> >>> matrix.vecSum(a,a.shape[0])
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: in method 'vecSum', argument 1 of type 'int *'
>
> How can I tell SWIG that my Integer NumPy array should represent a  
> int* array in C ?
>
> Thank you very much,
>
> Kevin
> <ATT00002.txt>

** Bill Spotz                                              **
** Sandia National Laboratories  Voice: (505)845-0170      **
** P.O. Box 5800                 Fax:   (505)284-0154      **
** Albuquerque, NM 87185-0370    Email: wfspotz@sandia.gov **








More information about the Numpy-discussion mailing list