如何将Python数组及其维度传递给Fortran并在子程序间使用?
可行的实现方案
方案1:用Fortran模块共享数组(推荐)
模块是Fortran中跨文件共享变量的标准方式,完全适配你的需求:
- 创建存储共享数组的模块文件(比如命名为
shared_arrays.f90):
module shared_arrays implicit none ! 声明共享数组和维度,显式加save属性确保变量在子程序调用间保留状态 real, dimension(:,:), allocatable, save :: my_array integer, save :: arr_rows, arr_cols end module shared_arrays
- 在所有需要使用数组的子程序中引用该模块
比如子程序文件sub1.f90:
subroutine sub1() use shared_arrays implicit none integer :: idx ! 直接使用模块中的my_array do idx = 1, arr_cols print *, "Row 1, Col ", idx, ": ", my_array(1, idx) end do end subroutine sub1
另一个子程序文件sub2.f90:
subroutine sub2() use shared_arrays implicit none ! 计算数组元素总和 print *, "Total sum of array: ", sum(my_array) end subroutine sub2
- 写初始化子程序接收Python传来的数组
创建init_arr.f90:
subroutine init_arr(input_arr, n_rows, n_cols) use shared_arrays implicit none real, dimension(n_rows, n_cols), intent(in) :: input_arr integer, intent(in) :: n_rows, n_cols ! 先释放旧内存再分配新空间 if (allocated(my_array)) deallocate(my_array) arr_rows = n_rows arr_cols = n_cols allocate(my_array(arr_rows, arr_cols)) my_array = input_arr end subroutine init_arr
- f2py编译所有文件
在终端执行:
f2py -c -m fortlib shared_arrays.f90 init_arr.f90 sub1.f90 sub2.f90
- Python端调用
import numpy as np import fortlib # 定义Python数组(注意用float64对应Fortran的real) py_array = np.array([[1.0,2.0,3.0],[4.0,5.0,6.0]], dtype=np.float64) rows, cols = py_array.shape # 初始化Fortran模块中的数组 fortlib.init_arr(py_array, rows, cols) # 调用各个子程序,它们会直接使用模块里的数组 fortlib.sub1() fortlib.sub2()
方案2:显式传递数组给每个子程序
如果不想用模块,最直接的方式就是每次调用子程序时都把数组和维度传进去:
- Fortran子程序示例(
sub1.f90):
subroutine sub1(input_arr, n_rows, n_cols) implicit none real, dimension(n_rows, n_cols), intent(in) :: input_arr integer, intent(in) :: n_rows, n_cols integer :: idx do idx = 1, n_cols print *, "Row 1, Col ", idx, ": ", input_arr(1, idx) end do end subroutine sub1
- 编译与调用
编译命令:
f2py -c -m fortlib sub1.f90 sub2.f90
Python调用:
import numpy as np import fortlib py_array = np.array([[1.0,2.0,3.0],[4.0,5.0,6.0]], dtype=np.float64) rows, cols = py_array.shape fortlib.sub1(py_array, rows, cols) fortlib.sub2(py_array, rows, cols)
这种方式虽然代码冗余,但不需要维护模块,适合子程序数量少的场景。
关键注意点
- 确保数组类型匹配:Python的
np.float64对应Fortran的real(8)或默认real(取决于编译器),避免类型不兼容。 - 用
intent(in)标记数组参数,明确告知f2py该数组是只读的,减少不必要的内存拷贝。 - 如果涉及多维数组,注意Fortran是列优先存储,Python默认是行优先,必要时在Python中用
np.asfortranarray()转换。
内容的提问来源于stack exchange,提问作者zyy
相关产品推荐
相关产品推荐

