1

I have Fortran code which I'd like to feed from Python with f2py. But I am not able to pass Numpy arrays of a known shape via f2py. (I'm on Python 2.7.10 and using gfortran and mingw32 as compilers).

Here is my Fortran code:

Subroutine test(nx,ny,mask)
  Integer, intent(inout) :: mask(ny,nx) 
  !f2py intent(in,out) mask
End

Which is called like this in Python:

from test import test
import numpy as np

nx = 2
ny = 2

mask = np.ones((nx,ny),dtype=int)

maskreturn = test(nx,ny,mask)

Running the script results in:

  error: (shape(mask,1)==nx) failed for 1st keyword nx: test:nx=2

I have no clue how to make it running (I'd need the correct passing of grids for a bigger model). Is there some terrible Fortran Noob mistake in there?

1
  • don't know if it matters, but i recommend explicitly declaring nx,ny integer in the subroutine. Commented Jun 2, 2016 at 13:08

1 Answer 1

1

The following seems to work for me

Fortran block in untitled.f90:

subroutine test(nx,ny,mask)
  integer, intent(in) :: nx, ny
  integer, dimension(nx,ny), intent(inout) :: mask
  !f2py intent(in,out) mask                                                                                                                                                                                         
  print*,nx,ny,mask
end subroutine test

Compile with:

f2py -c --fcompiler=gnu95 untitled.f90

In python do:

from untitled import test
import numpy as np
nx = 2 ; ny = 2
mask = np.ones((nx,ny),dtype=np.int32)
temp = test(mask,ny,nx) #Note the reversed order

I hope this helps, but I'm not experienced with f2py so can't explain more why this works.

Update After looking for potential duplicates I came across this answer which explains how/why the above works.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thanks! F2Py seems mightier than I though!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.