# [SciPy-user] Wrapping C libraries for Numeric integration

Robert Hetland hetland at tamu.edu
Tue Feb 7 11:52:30 CST 2006

```This is an excellent example -- I have just been wondering how to do
such things, and I would prefer f2py over swig, since it is more
familiar to me.

However, I can't seem to get the example to work.  It complies fine,
but I get an output array of all zeros (the same size as the input
array).  Any suggestions?

-Rob

On Feb 7, 2006, at 5:23 AM, Pearu Peterson wrote:

>
>
> 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)
>
>                           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
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.net
> http://www.scipy.net/mailman/listinfo/scipy-user

-----
Rob Hetland, Assistant Professor
Dept of Oceanography, Texas A&M University
p: 979-458-0096, f: 979-845-6331
e: hetland at tamu.edu, w: http://pong.tamu.edu

```