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.
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.
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)
来源:https://stackoverflow.com/questions/8487043/f2py-working-with-allocatable-arrays-in-fortran-being-invoked-through-python