F2Py:通过Python调用Fortran中的可分配数组
使用 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 个回答
-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)
0
看看这篇文章 http://www.shocksolution.com/2009/09/f2py-binding-fortran-python/,特别是里面的例子和相关的意思。
!f2py depend(len_a) a, bar
不过,作者没有提到如何生成不同大小的数组这个问题。