经过一些在线挖掘和试错,我仍然想知道如何通过 f2py 将字符串数组从 Python 传递到 Fortran。
我在 string.f90 中有 Fortran 子例程:
SUBROUTINE FOO(A)
CHARACTER*5,dimension(10),intent(inout):: A
PRINT*, "A=",A
END
然后我运行 f2py -m mystring -c string.f90。 编译成功。
python session 在 test.py 中:
import mystring
import numpy as np
nobstot=10
xstring=np.empty(nobstot,dtype='S5')
xstring[0]="ABCDE"
mystring.foo(xstring)
运行python test.py,出现错误信息:
1-th dimension must be 5 but got 0 (not defined).
Traceback (most recent call last) :
File "test.py", line 6, in <module>
mystring.foo(xstring)
mystring.error: failed in converting 1st argument `a' of mystring.foo to C/Fortran array
在f2py编译步骤中,调用了gfortran和gcc编译器。
在 >>> print mystring.foo.__doc__ 之后,有:
foo(a)
Wrapper for ``foo``.
Parameters
---------
a : in/output rank-2 array('S') with bounds (10,5)
所以,我尝试将 test.py 作为:
import mystring
import numpy as np
nobstot=10
xstring=np.empty((nobstot,5),dtype='S1')
print xstring.shape
xstring[0]="ABCDE"
mystring.foo(xstring)
然后运行python test.py,报错信息为:
Traceback (most recent call last):
File "test.py", line 7, in <module>
mystring.foo(xstring)
ValueError: failed to initialize intent(inout) array -- input 'S' not compatible to 'c'
请您参考如下方法:
首先,要将字符串数组传递给 Fortran,在 Python 中,您必须创建一个形状为 (<number of strings>, <string length>) 的字符数组。 ,填充其内容,然后将 char 数组传递给 f2py 生成的函数。使用您的示例:
xstring = np.empty((nobstot, 5), dtype='c')
xstring[0] = "ABCDE"
xstring[1] = "FGHIJ"
mystring.foo(xstring)
为了让它工作,您还需要更改您的 Fortran 代码:
subroutine foo(A)
character*5, dimension(10), intent(in) :: A
print*, "A(1)=",A(1)
print*, "A(2)=",A(2)
end
注意 intent(inout)替换为 intent(in) .这是因为 Python 中的字符串以及 numpy 字符串数组中的字符串是不可变的,但在 Fortran 中它们可能不是。因此,Python 字符串的内存布局不能简单地传递给 Fortran 函数,用户必须如上所述重新组织字符串数据。
其次,如果您的 Fortran 代码更改了字符串,如 intent(inout) 的用法建议,您需要将此类字符串参数声明为 intent(in, out) ,例如,通过使用 f2py 指令。下面是一个完整的示例:
subroutine foo(A)
character*5, dimension(10), intent(inout) :: A
!f2py intent(in, out) A
print*, "A(1)=",A(1)
print*, "A(2)=",A(2)
A(1)="QWERT"
end
F2py调用:
f2py -m mystring -c string.f90
Python 测试脚本:
import mystring
import numpy as np
nobstot = 10
xstring = np.empty((nobstot, 5), dtype='c')
xstring[0] = "ABCDE"
xstring[1] = "FGHIJ"
xstring = mystring.foo(xstring)
print("xstring[0]=",string[0].tostring())
print("xstring[1]=",string[1].tostring())
控制台输出:
A(1)=ABCDE
A(2)=FGHIJ
xstring[0]= QWERT
xstring[1]= FGHIJ
