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.

4
  • Could you also post the python code? Commented Dec 14, 2011 at 15:16
  • The f2py list would also be a good place to ask, the responses are usually quite fast. Commented Dec 14, 2011 at 21:25
  • @VladimirF The code I used to invoke it in Python is: import test; print test.select([0,1,2,9,5]) assuming that I compiled it already as test.pyd. Commented Dec 15, 2011 at 8:21
  • @bdforbes Thanks for the hint. I submitted and encouraged the list having a look on this page and giving me some solution ideas. Commented Dec 15, 2011 at 8:25

2 Answers 2

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.

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

1 Comment

Thanks for the link. However the problem is we don't know how much the size of output array is!
-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)

2 Comments

No, f2py handles assumed shape arrays just right.
OK. Nice to learn. But I don't understand how it can do that in a portable manner...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.