【问题标题】:Fortran procedure pointers as argument. Error: Invalid procedure argument at (1)Fortran 过程指针作为参数。错误: (1) 处的过程参数无效
【发布时间】:2021-03-03 17:46:32
【问题描述】:

我试图通过使用指针将一个函数作为另一个函数的参数。我不断收到错误消息:Error: Invalid procedure argument at (1)。关于主程序中 diff 中的参数 f_ptr。有谁知道如何解决这个问题?

module functions
contains

function f(x) result(y)
    double precision x, y
    y = sin(x)
end function f

end module

MODULE numerical_math
contains
function diff(f, x, degree) result(df)
    double precision, intent(in) :: x
    double precision :: h, df
    integer :: degree, i, j
    integer, allocatable, dimension(:) :: lst
    pointer :: f
    interface
        function f(x) result(y)
            double precision :: x, y
        end function f
    end interface

    ...

end function diff
END MODULE numerical_math

program main
    use numerical_math
    use functions
    implicit none
    integer :: first
    procedure (f), pointer :: f_ptr => null ()
    f_ptr => f
    print *, f_ptr(1.d0)

    do first = 1,9
        print *, diff(f_ptr, 0.d0, first)
    end do    
end program main

【问题讨论】:

  • 在传递函数时根本不需要函数指针。函数指针仅在 Fortran 2003 中添加用于更高级的东西,例如存储函数地址并在以后更改它以供其他使用。你只需要普通的函数参数。
  • @SamWoef 您使用的是哪个编译器和版本?
  • 我在 netbeans IDE 上使用 mingw32-gcc-fortran
  • 如果您在maindiff 中调用diff(f, 0.d0, first) 会发生什么情况?删除pointer 行?
  • 还是同样的错误。说清楚,我离开界面吧?

标签: pointers fortran procedure


【解决方案1】:

我猜您的 diff 函数应该只接收一个函数作为参数,并且您不需要更改该函数(即您不想更改目标函数)。 然后你只需要删除diff函数中的pointer :: f行:

function diff(f, x, degree) result(df)
    double precision, intent(in) :: x
    double precision :: h, df
    integer :: degree, i, j
    integer, allocatable, dimension(:) :: lst
    ! pointer :: f  REMOVE THIS LINE
    interface
        function f(x) result(y)
            double precision :: x, y
        end function f
    end interface

    ...

end function diff

【讨论】:

  • (不是OP):因为接口声明,类型声明是隐式的?
  • @TasosPapastylianou 对于数据对象没有 type 声明,而是 interface 声明。如果您需要 pointer 属性,那么您可以使用 procedure(f_interface), pointer :: f 在其他地方定义 abstract interface f_interface 的东西。
【解决方案2】:

如果您遇到同样的问题,我通过在 Fortran 95 中制作项目来解决该问题。在 Fortran 95 中,当您使用 Jack 的建议时它会编译(删除 pointer :: f 行并将函数作为参数而不是指针) .我在 Fortran 90 中没有找到解决该问题的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多