在多个扩展模块之间使用F2PY共享Fortran 90模块数据

2024-04-20 15:12:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在许多自编译的F2PY扩展模块之间共享fortran90模块中的数据。F2PY的文档说这是不可能的,因为Python通常是如何导入共享库的。在

F2PY generates wrappers to common blocks defined in a routine signature block. Common blocks are visible by all Fortran codes linked with the current extension module, but not to other extension modules (this restriction is due to how Python imports shared libraries).

[...]

The F2PY interface to Fortran 90 module data is similar to Fortran 77 common blocks.

Link to Documentation

由于我必须使用大约100个嵌套的Fortran 90子例程,因此需要在它们之间共享数据。有什么建议吗?在

我考虑过将每个变量作为参数传递给每个子例程,然后返回变量,但这听起来有点不对。在


Tags: 模块to数据文档isextensioncommon例程
1条回答
网友
1楼 · 发布于 2024-04-20 15:12:16

虽然只是一种尝试和错误的方法,但是如何将变量模块和所有的子例程放入一个文件中并用f2py(*1)编译它?例如。。。在

mytest.f90:

include "vars.f90"
include "sub1.f90"
include "sub2.f90"

变量f90:

^{pr2}$

子1.f90:

subroutine sub1
    use vars, only: n
    implicit none
    print *, "sub1: n = ", n
end

子2.f90:

subroutine sub2
    use vars, only: n
    implicit none
    print *, "sub2: n = ", n
    print *, "adding 1 to n"
    n = n + 1
    print *, "n = ", n
end

编译:

f2py -c -m mytest mytest.f90

测试:

$ /usr/local/bin/python3
>>> import mytest
>>> mytest.vars.n
array(100, dtype=int32)
>>> mytest.sub1()
 sub1: n =          100
>>> mytest.sub2()
 sub2: n =          100
 adding 1 to n
 n =          101
>>> mytest.sub2()
 sub2: n =          101
 adding 1 to n
 n =          102
>>> mytest.vars.n = 777
>>> mytest.sub2()
 sub2: n =          777
 adding 1 to n
 n =          778

(*1)在上面的情况下,简单地将所有文件名赋给f2py就足够了,例如

$ f2py -c -m mytest vars.f90 sub1.f90 sub2.f90

相关问题 更多 >