[SciPy-user] Wrapping C libraries for Numeric integration

Pearu Peterson pearu at scipy.org
Tue Feb 7 05:23:59 CST 2006



On Tue, 7 Feb 2006, Bryan Cole wrote:

> What's the best approach for wrapping C libraries where the
> inputs/outputs are C arrays (which I want to pass to/from Numeric
> arrays)?
>
> I'm a regular SWIG user, but I don't have any typemaps to handle
> C-array-to-Numeric conversion and I can't see any distributed with SWIG.
> What approach is used by SciPy? (I know scipy is mostly fortran routines
> but surely you have a few C ones?).

f2py can be easily be used also wrapping C libraries if writing some 
Fortran-like syntax (see f2py usersguide) does not scare you. Here's a 
simple example:

/* File foo.c */
void foo(int n, double *x, double *y) {
   int i;
   for (i=0;i<n;i++) {
     y[i] = x[i] + i;
   }
}

! File m.pyf
python module m
interface
   subroutine foo(n,x,y)
     intent(c) foo                 ! foo is a C function
     intent(c)                     ! all foo arguments are considered as C based
     integer intent(hide), depend(x) :: n=len(x)  ! n is the lenght of input array x
     double precision intent(in) :: x(n)   ! x is input array (or  arbitrary sequence)
     double precision intent(out) :: y(n)  ! y is output array, see code in foo.c
   end subroutine foo
end interface
end python module m

# File setup.py
def configuration(parent_package='',top_path=None):
     from numpy.distutils.misc_util import Configuration
     config = Configuration('',parent_package,top_path)

     config.add_extension('m',
                          sources = ['m.pyf','foo.c'])
     return config
if __name__ == "__main__":
     from numpy.distutils.core import setup
     setup(**configuration(top_path='').todict())

Building and testing module m thats function foo calls C function:

   python setup.py build_src build_ext --inplace

   python
>>> import m
>>> print m.foo.__doc__
foo - Function signature:
   y = foo(x)
Required arguments:
   x : input rank-1 array('d') with bounds (n)
Return objects:
   y : rank-1 array('d') with bounds (n)

>>> m.foo([1,2,3,4,5])
array([ 1.,  3.,  5.,  7.,  9.])
>>>

Regards,
Pearu



More information about the SciPy-user mailing list