【问题标题】:Error occurs when coming back from subroutine of fortran by numpy.f2pynumpy.f2py 从 fortran 的子程序返回时发生错误
【发布时间】:2020-05-17 09:51:32
【问题描述】:

我使 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带来了错误。

【问题讨论】:

  • 看起来你在 pythonn 中调用了没有参数的函数,并且在 fortran 子例程中你期望一个数组(指令intent(out) 只是说内容应该/将在子例程中设置)。仍然是一条奇怪的消息,但可能是一个指针。
  • 使用 d=hoge.hoge() 运行会带来相同的信息..
  • d 是一个参数,而不是子例程的返回值。在 C 语言中,子程序是一个 void 函数。
  • 我也意识到,如果我做一个小小的改变......它会起作用。我更新了问题。
  • 你的更新版本是要走的路。查看print(hoge.hoge.__doc__) 的输出,您会看到f2py 将您的原始声明解释为具有默认浮点数d : rank-3 array('F') with bounds (5,10,15) 的复杂。但是,替代声明给出了所需的双重结果d : rank-3 array('D') with bounds (5,10,15)

标签: python fortran f2py


【解决方案1】:

根据F2PY User Guide and Reference Manual

Currently, F2PY can handle only &lttype spec&gt(kind=&ltkindselector&gt)
declarations where &ltkindselector&gt 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'}}

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

【讨论】:

    猜你喜欢
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2016-06-11
    • 2012-07-30
    相关资源
    最近更新 更多