繁体   English   中英

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

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

使用F2Py编译适合在Python使用的Fortran例程,在使用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帖子。

请看一下本文http://www.shocksolution.com/2009/09/f2py-binding-fortran-python/ ,尤其是其中的示例及其含义

!f2py depend(len_a) a, bar

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

您的函数应声明为:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM