F2Py:使用Python调用Fortran中的可分配数组

时间:2011-12-13 09:42:40

标签: python fortran dynamic-data runtime-error f2py

使用F2Py编译适合在Fortran中使用的Python例程,在使用F2Py时,以下代码成功编译为gfortran编译器,但是,在调用Python时,它会引发运行时错误! 有何评论和解决方案?

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

可以找到类似的StackOverflow帖子here

2 个答案:

答案 0 :(得分:0)

看一下这篇文章http://www.shocksolution.com/2009/09/f2py-binding-fortran-python/,特别是

的例子和含义
!f2py depend(len_a) a, bar

然而,作者没有涉及生成不同大小的数组的问题。

答案 1 :(得分:-2)

你的职能应该宣布:

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
   ...

实际上,Python是用C语言编写的,你的Fortran例程必须遵循Iso_C_binding的规则。特别是,禁止使用假定的形状数组。

无论如何,我更喜欢子程序:

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

ny是真正用于y的大小(ny <= nx)