【问题标题】:How make external function work with f2py?如何使外部函数与 f2py 一起工作?
【发布时间】:2022-06-14 18:08:22
【问题描述】:

我正在尝试使用f2py 编译一段旧的 Fortran 代码,以便可以在 Python 中调用它。 但是,有一部分涉及外部功能不起作用。 这是一个最小的工作示例,首先是test.f

      function f(x)
      implicit double precision (a-z)

      f = x * x

      return
      end function f

      subroutine gauss(fun)
      implicit double precision (a-h, j-z)
      ! external fun

      x = 1.5
      write(*,*) fun(x)

      return
      end subroutine gauss

并用makefile编译后

f2py -c --quiet --fcompiler=gnu95 \
        --f90flags=“-Wtabs” \
        -m test \
        test.f

我使用 Python 调用它

import test
f = lambda x: x
test.gauss(test.f)

并得到错误TypeError: test.gauss() 1st argument (fun) can’t be converted to double

第二次 尝试中,我取消注释子例程 gauss 中的行 external fun 并在编译期间收到以下错误消息

/tmp/tmpet9sk3e9/src.linux-x86_64-3.7/testmodule.c: In function ‘cb_fun_in_gauss__user__routines’:
/tmp/tmpet9sk3e9/src.linux-x86_64-3.7/testmodule.c:313:8: error: variable or field ‘return_value’ declared void

我现在没有想法,任何帮助将不胜感激!

【问题讨论】:

标签: python fortran f2py


【解决方案1】:

我(部分)想通了:f2py 需要您明确指定函数的使用。 方法如下:

      function f(x)
      implicit double precision (a-z)

      f = x * x

      return
      end function f

      subroutine gauss(fun)
      implicit double precision (a-h, j-z)
      !! <-------- updates starts HERE
      external fun
!f2py real*8 y
!f2py y = fun(y)
      double precision fun
      !! <-------- updates ends HERE

      x = 1.5
      write(*,*) fun(x)

      return
      end subroutine gauss

然后使用编译它

main:
    f2py -c --quiet --fcompiler=gnu95 \
        --f90flags=“-Wtabs” \
        -m test \
        test.f

你可以测试

import test
f = lambda x: x
test.gauss(test.f)
test.gauss(f)

并看到外部函数适用于 Fortran 和 Python 函数。


两个旁注:

  1. 虽然documentation!f2py intent(callback) fun 是必要的,但我发现没有它代码也可以工作。
  2. 您可以使用相同的语法指定多个外部函数,甚至可以为所有这些函数使用相同的虚拟输入变量y(尽管这可能不是一个好习惯)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2015-10-13
    • 2018-11-15
    相关资源
    最近更新 更多