F2Py: Working with allocatable arrays in Fortran being invoked through Python

拜拜、爱过 提交于 2020-01-01 19:12:32

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/8487043/f2py-working-with-allocatable-arrays-in-fortran-being-invoked-through-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!