2

Using F2Py to compile Fortran routines being suitable to be used within Python, the following piece of code is successfully compiled configured gfortran as the compiler while using F2Py, however, at the time of invoking in Python it raises a runtime error!
Any comments and solutions?

function select(x) result(y)
   implicit none
   integer,intent(in):: x(:) 
   integer:: i,j,temp(size(x))
   integer,allocatable:: y(:)
   j = 0
   do i=1,size(x)
      if (x(i)/=0) then
         j = j+1
         temp(j) = x(i)
      endif
   enddo
   allocate(y(j))
   y = temp(:j)
end function select

A similar StackOverflow post can be found here.

Community
  • 1
  • 1
Developer
  • 8,258
  • 8
  • 49
  • 58

2 Answers2

0

Take a look at this article http://www.shocksolution.com/2009/09/f2py-binding-fortran-python/ , especially at the example and the meaning of

!f2py depend(len_a) a, bar

However, the author does not touch of the problem of generating a an array of different size.

-2

Your function should be declared :

function select(n,x) result(y)
   implicit none
   integer,intent(in) :: n
   integer,intent(in) :: x(n) 
   integer :: y(n) ! in maximizing the size of y
   ...

Indeed, Python is written in C and your Fortran routine must follow the rules of the Iso_C_binding. In particular, assumed shape arrays are forbidden.

In any case, I would prefer a subroutine :

  subroutine select(nx,y,ny,y)
     implicit none
     integer,intent(in) :: nx,x(nx)
     integer,intent(out) :: ny,y(nx)

ny being the size really used for y (ny <= nx)

Francois Jacq
  • 1,244
  • 10
  • 18