将函数传递给子例程时,虚拟过程'f'中的接口不匹配

js9*_*947 2 fortran fortran90

我正在尝试编写一个有两个参数的子程序(用于最小化):

  • 一个x任意长度的数组
  • f获取该长度数组并返回标量的函数

示例模块:

module foo

contains

  subroutine solve(x, f)
    real, dimension(:), intent(inout) :: x
    interface
      real pure function f(y)
        import x
        real, dimension(size(x)), intent(in) :: y
      end function
    end interface

    print *, x
    print *, f(x)
  end subroutine

end module
Run Code Online (Sandbox Code Playgroud)

和测试程序:

use foo

real, dimension(2) :: x = [1.0, 2.0]

call solve(x, g)

contains

  real pure function g(y)
    real, dimension(2), intent(in) :: y

    g = sum(y)
  end function

end
Run Code Online (Sandbox Code Playgroud)

gfortran失败了:

call solve(x, g)
              1
Error: Interface mismatch in dummy procedure 'f' at (1): Shape mismatch in dimension 1 of argument 'y'
Run Code Online (Sandbox Code Playgroud)

如果我改变size(x) => 2那么它编译(并运行)很好.如果我改变它也可以正常工作 : => 2.但这些解决方案都没有让我得到我想要的东西.

有关如何实现这一目标的任何想法?

M. *_* B. 5

怎么样:

interface
  real pure function f(y)
    real, dimension(:), intent(in) :: y
  end function
end interface
Run Code Online (Sandbox Code Playgroud)

将参数传递solve给函数时,将自动传递数组的大小.您不需要创建界面的这一部分.