2016-10-16 29 views
0

我有一個子程序,計算一個大型數組並將其寫入文件。我試圖將其轉換爲返回該數組的函數。然而,我得到了一個非常奇怪的錯誤,這似乎與我返回一個數組有關。當我嘗試返回一個浮點數(作爲測試)時,它工作得很好。編譯f90函數,返回數組使用f2py

這裏的MWE,這是我從蟒蛇打電話與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����[email protected](����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.)

+0

@JonatanÖström下面是一個新問題。這樣你可以測試我的MWE。 – TomCho

+1

這些代碼片段是相同的。 –

+0

@ŁukaszRogalski我的壞。只是修復它。 – TomCho

回答

1

我認爲這個問題來自缺乏顯式接口的地方。 (不確定可能是別人可以更精確地指出什麼是問題。)

即使我不確定我的解釋,我有2個工作案例。 將您的功能更改爲子程序將您的功能放入模塊(它自己生成顯式接口)可解決您提到的問題。

下面的腳本仍然可以從python中調用,如my_sub('dir', 'postpfile', 150, 90.)

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工作,包括你的函數(顯式接口的假設存在是關鍵)

我希望有人將完成/正確我的答案。