[Numpy-discussion] f2py with allocatable arrays

Sturla Molden sturla@molden...
Tue Jul 3 19:23:37 CDT 2012

Den 03.07.2012 20:38, skrev Casey W. Stark:
> Sturla, this is valid Fortran, but I agree it might just be a bad 
> idea. The Fortran 90/95 Explained book mentions this in the 
> allocatable dummy arguments section and has an example using an array 
> with allocatable, intent(out) in a subrountine. You can also see this 
> in the PDF linked from 
> http://fortranwiki.org/fortran/show/Allocatable+enhancements.

Ok, so it's valid Fortran 2003. I never came any longer than to Fortran 
95 :-) Make sure any Fortran code using this have the extension .f03 -- 
not .f95 or .f90 -- or it might crash horribly.

> I have never used array pointers in Fortran, but I might give this a 
> shot. Are there any problems returning pointers to arrays back to 
> python though?

In the Fortran 2003 ISO C binding you can find the methods F_C_POINTER 
and C_F_POINTER that will convert between C and Fortran pointers.

A Fortran pointer is an array struct, much like a NumPy view array, and 
has dimensions and strides. It can reference contiguous and 
discontiguous blocks of memory.  A C pointer is just a memory address. 
You must therefore use special methods to convert between C and Fortran 
pointers. There is an extension to Cython called fwrap that will 
generate this kind of boiler-plate code for conversion between NumPy and 
Fortran using the ISO C bindings in Fortran 2003. It is an alternative 
to f2py, though less mature.

At the binary level, a Fortran pointer and an allocatable array usually 
have the same representation. But there are semantic differences between 
them. In Fortran 2003, pointers are less useful than in Fortran 95, 
except when interfacing with C through the ISO C bindings. That is 
because you can put allocatable arrays as memers in derived types, and 
(as I learned today) use them as dummy variables. In Fortran 95 those 
would be common cases for using pointers.

By the way: The Fortran counter part to a C pointer is a Cray pointer, 
which is a common non-standard extension to the language. A Cray 
pointer, when supported, is a pair of variables: one storing the address 
and the other dereferencing the address.


More information about the NumPy-Discussion mailing list