由于工作需要把Python和Fortran连接在一起,最近去学了以下怎么用f2py。f2py的具体用法见 f2py Manual
- 错误信息
在Fortran里,我们往往喜欢用下面这种方法来声明数据的类型
module types
implicit none
integer, parameter :: dp = kind(1.0d0), sp = kind(1.0)
end module types
module consts_dp
use types
implicit none
real(dp), public, parameter :: pi =&
& 3.141592653589793238462643383279502884197_dp
但这种声明数据类型的方法,在用f2py去生成Python module的时候会遇到一些问题。
首先,生成Python module的过程中不会报错,不过你会看到下面这样的信息
getctype: "real(kind=dp)" is mapped to C "float" (to override define dict(real = dict(dp="<C typespec>")) in /media/xx/xxx/xxxx/xxx/xx/f2py_trial/.f2py_f2cmap file).
其次,当你在Python里调用这个来自Fortran的module时,如果你用到了上面这种声明数据类型的方法,你可能会发现f2py不能很好地把double precision在Fortran和Python之间传递。Reference [1]给了一个很生动很好的例子。
- 解决办法
Refernce [1]中给出了三种解决方法,其中第二种方法可能是最经典的。Reference [1]中的第二种方法参考了Reference [2]。
我们回头看f2py返回的信息,里面明确讲了f2py把Fortran中的“real(kind=dp)”映射为C中的"Float"。如果想改写这种映射,可以在当前目录下的.f2py_f2cmap中定义
dict(real = dict(dp="<C typespec>") #把这里的'C typespec'替换成需要的数据类型
重新定义完映射之后,再用f2py连接一次Python和Fortran就可以了。
- Reference