从 numpy.f2py 的 fortran 子程序返回时出错

Error occurs when coming back from subroutine of fortran by numpy.f2py

我使 hoge 尽可能简单,但错误仍然存​​在。 请告诉我有什么问题。

这是我的 Fortran 子例程代码。

subroutine hoge(d)
  complex(kind(0d0)), intent(out):: d(5,10,15) ! 5 10 15 does not have special meanings..

  ! these two lines works..
  ! integer, parameter :: dp = kind(0d0)
  ! complex(dp), intent(out) :: d(5,10,15)

  do i=1,15
    do j=1,10
      do k=1,5
        d(k,j,i)=0
      enddo
    enddo
  enddo
  ! instead 
  ! d(1:5,1:10,1:15)=0 or
  ! d(:,:,:)=0 also brings the error.
  !
  print*,'returning'
  return
end subroutine hoge

我想使用 Fortran 子例程。我编译如下

python -m numpy.f2py -c hoge.f90 -m hoge

并如下使用

import hoge
hoge.hoge()

那么结果就是下面三行:

Returning
double free or corruption (out)
Aborted (core dumped)

我完全不知道...请告诉我有什么问题。

当线路发生如下变化时

do j=1,10   -> do j=1,5

错误没有发生...(供您参考..) 1..6 带来错误。

根据 F2PY User Guide and Reference Manual:

Currently, F2PY can handle only <type spec>(kind=<kindselector>)
declarations where <kindselector> is a numeric integer (e.g. 1, 2,
4,…), but not a function call KIND(..) or any other expression.

因此,您的代码示例中的声明 complex(kind(0d0)) 正是 f2py 无法解释的 函数调用或其他表达式 的类型。

正如您所发现的(但在代码中被注释掉),一种变通方法是首先生成一个整数类型说明符 (integer, parameter :: dp = kind(0d0)),然后在复数变量的种类说明符中使用它complex(dp).

如果像这样更改 Fortran 源代码不适合您,该文档进一步概述了 映射文件(默认名称 .f2py_f2cmap 或使用可以创建和使用命令行标志 --f2cmap <filename>)。在您的情况下,您可以例如使用具有以下内容的默认文件:

$ cat .f2py_f2cmap
{'complex': {'KIND(0D0)': 'complex_double'}}

并像以前一样编译,以获得所需的行为。