F2PY 看不到模块范围的变量

Yux*_*ang 1 python fortran numpy fortran90 f2py

很抱歉对 Fortran 90 和 f2py 都不熟悉。

我使用的是 Windows 64 位、Python 3.4 64 位、gfortran。Numpy 版本是 1.9.1,我在 gnu.py 中评论了“raise NotImplementedError("Only MS compiler supported with gfortran on win64")”,如以下链接所示:http ://scientificcomputingco.blogspot.com.au /2013/02/f2py-on-64bit-windows-python27.html

我在 fortran 中有一个模块,编写如下,带有模块范围变量dp

! testf2py.f90
module testf2py
    implicit none
    private
    public dp, i1
    integer, parameter :: dp=kind(0.d0)
contains
    real(dp) function i1(m)
        real(dp), intent(in) :: m(3, 3)
        i1 = m(1, 1) + m(2, 2) + m(3, 3)
        return
    end function i1
end module testf2py
Run Code Online (Sandbox Code Playgroud)

然后,如果我跑 f2py -c testf2py.f90 -m testf2py

它会报告错误,指出未声明 dp。

如果我将模块范围复制到函数范围,它会起作用。

! testf2py.f90
module testf2py
    implicit none
    private
    public i1
    integer, parameter :: dp=kind(0.d0)
contains
    real(dp) function i1(m)
        integer, parameter :: dp=kind(0.d0)
        real(dp), intent(in) :: m(3, 3)
        i1 = m(1, 1) + m(2, 2) + m(3, 3)
        return
    end function i1
end module testf2py
Run Code Online (Sandbox Code Playgroud)

然而,这看起来并不是最好的编码实践,因为它非常“湿”。

有任何想法吗?

War*_*ser 5

这是一个变通方法,将其中dp移动到types模块,并将use types语句添加到函数中i1

! testf2py.f90

module types
    implicit none
    integer, parameter :: dp=kind(0.d0)
end module types

module testf2py
    implicit none
    private
    public i1
contains
    real(dp) function i1(m)
        use types
        real(dp), intent(in) :: m(3, 3)
        i1 = m(1, 1) + m(2, 2) + m(3, 3)
        return
    end function i1
end module testf2py
Run Code Online (Sandbox Code Playgroud)

在行动:

In [6]: import numpy as np

In [7]: m = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

In [8]: import testf2py

In [9]: testf2py.testf2py.i1(m)
Out[9]: 150.0
Run Code Online (Sandbox Code Playgroud)

这种变化类似于我在这个答案中描述的第三个选项:f2py: Specifying real precision in fortran when interface with python?