[SciPy-user] Is it possible to pass Fortran derived data types to Python via C and SWIG?
Berthold Höllmann
berthold at xn--hllmanns-n4a.de
Sun Nov 30 16:38:14 EST 2008
Matthieu Brucher <matthieu.brucher <at> gmail.com> writes:
>
> 2008/11/30 David Cournapeau <david <at> ar.media.kyoto-u.ac.jp>:
> > John Salvatier wrote:
> >> I have a Fortran 90 algorithm which uses a derived data type to return
> >> data, and I would like to make a python wrapper for this algorithm. I
> >> understand that f2py cannot wrap derived data types; is it possible to
> >> do so with a C interface for the Fortran algorithm and SWIG? I would
> >> have to pass the derived data type into a C struct and then to Python.
> >
> > It is possible as long as you can pass the structure from fortran to C.
> > I don't know anything about Fortran derived data types, but if it is a
> > non trivial object (more than a set of fundamental types), I am afraid
> > it will be difficult. Does F90 supports POD data ? Otherwise, you will
> > need a scheme for marshalling your data from Fortran to C (to match
> > exactly how the structure would look like in C at the binary level).
> >
> > David
>
> I've read an article (I don't remember where though, possibly CiSE)
> that stated that it's really not an easy task, as each Fortran
> compiler can do as it pleases it. So depending on the compiler and the
> Fortran standard, it can be possible, or not. So as there are no
> guaranties, you should write a function that transforms the Fortran
> structure in several pieces that are then passed to the C function.
>
> Matthieu
A feasible way to achieve this would be to write a Fortran wrapper
around your routine(x) that decomposes your derived data type to
standard types and exposes these in the interface. Than you can compose
the derived data type again in the wrapper and pass it to the original
routine. ::
module geom
type Point
real :: x, y
end type Point
type Circle
type (Point) :: Center
real :: Radius
end type Circle
end module geom
subroutine test(c)
use geom
type (Circle) :: c
print*, c%Radius
print*, c%Center%X
print*, c%Center%Y
end subroutine test
subroutine w_test(x, y, r)
use geom
real :: x, y, z
type (Circle) :: C
c%Radius = r
c%Center%X = x
c%Center%Y = y
call test(c)
end subroutine w_test
Wrapping w_test should be trivial using f2py
Regards
Berthold
More information about the SciPy-User
mailing list