使用 f2py 编译 returns 数组的 f90 函数

Compiling f90 function that returns array using f2py

我有一个计算大数组并将其写入文件的子例程。我正在尝试将其转换为 return 数组的函数。但是,我收到一个非常奇怪的错误,这似乎与我正在 returning 数组有关。当我尝试 return 一个浮动(作为测试)时,它工作得很好。

这是 MWE,我从 python 调用 mwe('dir', 'postpfile', 150, 90.):

FUNCTION mwe(dir, postpfile, nz, z_scale)
IMPLICIT NONE

INTEGER         :: nz
REAL(KIND=8)    :: z_scale
CHARACTER(len=100)      :: postpfile
CHARACTER(len=100)         :: dir
REAL(kind=8)  :: mwe

print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale

mwe = 4.5d0
END FUNCTION mwe

效果很好,打印结果符合预期:

 dir dir                                                                                                 
 postpfile postpfile                                                                                           
 nz          150
 Lz    90.000000000000000     

但是,如果我将函数定义为数组:

FUNCTION mwe(dir, postpfile, nz, z_scale)
IMPLICIT NONE

INTEGER         :: nz
REAL(KIND=8)    :: z_scale
CHARACTER(len=100)      :: postpfile
CHARACTER(len=100)         :: dir
REAL(KIND=8),DIMENSION (2,23)   :: mwe

print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale

mwe = 4.5d0
END FUNCTION mwe

然后打印如下:

 dir postpfile                                                                                           
 postpfile ��:����������k�� 2����V@(����H���;�!��v
 nz            0
Segmentation fault (core dumped)

我是 运行 f2py 版本 2,NumPy 1.11.1 和 Python 3.5.1.

编辑

我正在使用 f2py -c -m fmwe fmwe.f90 进行编译,并使用 mwe('dir', 'postpfile', 150, 90.) 调用函数。

我认为问题出在某个地方,因为缺少显式接口。 (不确定其他人是否可以更准确地指出问题所在。)

虽然我不确定我的解释,但我有 2 个工作案例。 将您的函数更改为子例程将您的函数放入模块(它自己生成显式接口)可以解决您提到的问题。

下面的脚本仍然可以像 my_sub('dir', 'postpfile', 150, 90.) 从 python 调用。

subroutine my_sub(mwe, dir, postpfile, nz, z_scale)
implicit none

integer,intent(in)             :: nz
real(KIND=8),intent(in)        :: z_scale
chracter(len=100),intent(in)   :: postpfile
character(len=100), intent(in) :: dir
real(KIND=8), intent(out)      :: mwe(2,23)

print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale

mwe = 4.5d0
end subroutine my_sub

如果您在模块中使用该函数,则需要从 python 进行调用,方式略有不同; test('dir', 'postpfile', 150, 90.).

module test

contains 
function mwe(dir, postpfile, nz, z_scale)
implicit none

integer            :: nz
real(KIND=8)       :: z_scale
chracter           :: postpfile
character(len=100) :: dir
real(KIND=8)       :: mwe(2,23)

print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale

mwe = 4.5d0
end function mwe

end module test

我没试过,但它可能会与适当的 Fortran interface 一起工作,包括你的函数。(假设显式接口的存在是关键)

希望有人会complete/correct回答我的问题。