You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

f2py封装含inout参数的Fortran子程序后无法修改输入数组如何解决

问题原因
  • 参数传递类型不匹配:你传入的是Python原生列表,f2py处理原生列表时会自动生成临时Fortran数组副本,子程序修改的是副本而非原列表,执行结束后副本不会回写到原列表,因此原列表的值无变化。
  • f2py未识别参数读写属性:你没有给Fortran子程序的array参数显式声明intent(inout),f2py默认会将假定形状数组(dimension(:)定义的数组)推断为只读的intent(in)类型,即便传入可直接操作内存的结构,也不会回写修改结果。
解决方法

1. 修改Fortran代码,显式声明参数属性

给array参数加上intent(inout),明确告诉f2py该参数需要读写:

module sorting 
    use iso_fortran_env, only: i4 => int32, i8 => int64
    implicit none
contains
    subroutine bubbleSort(array)
        implicit none
        ! 新增intent(inout)声明
        integer, dimension(:), intent(inout) :: array
        integer :: i, j, tem
        i = size(array)
        do while (i > 1)
            do j = 1, i - 1 
                if (array(j) > array(j + 1)) then
                    tem = array(j)
                    array(j) = array(j + 1)
                    array(j + 1) = tem
                end if 
            end do
            i = i - 1
        end do 
    end subroutine bubbleSort
end module sorting 

修改后依然用原命令编译即可:f2py -c sorting.f90 -m sortF

2. Python端传入连续存储的numpy数组

numpy数组具备和Fortran兼容的连续同类型内存布局,可以直接传递内存指针而非拷贝副本,调用示例如下:

from sortF import sorting
import numpy as np

# 要和Fortran的整数类型匹配,这里用int32对应Fortran默认整数类型
x = np.array([1, 2, 5, 3], dtype=np.int32)
sorting.bubblesort(x)
print(x) # 输出 [1 2 3 5]

内容的提问来源于stack exchange,提问作者ComplicatedPhenomenon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:00:02