2013-11-28 26 views
2
返回一個值

考慮下面的Fortran子程序,在test.f定義:如何從一個Python回調Fortran中使用F2Py

subroutine test(py_func) 

use iso_fortran_env, only stdout => output_unit 

external py_func 

integer :: a 
integer :: b 

a = 12 
write(stdout, *) a 

b = py_func(a) 
write(stdout, *) b 

end subroutine 

而且下面的Python代碼,在call_test.py定義:

import test 

def func(x): 
    return x * 2 

test.test(func) 

具有以下(Intel編譯)編譯:

python f2py.py -c test.f --fcompiler=intelvem -m test 

我希望這是輸出,當我運行測試:

 12 
     24 

但我居然得到這樣的:

 12 
     0 

看起來好像b正在用默認值,而不是test結果初始化。的12打印輸出到控制檯後

!f2py intent(callback) py_func 
     external py_func 
!f2py integer y,x 
!f2py y = py_func(x) 

但我的程序崩潰:我已經嘗試使用在Fortran以下。

任何想法可能是怎麼回事?造成這次事故的原因是一種獎勵,但我真的只是想在這個時候獲得一個簡單的回調工作。

回答

0

我不主張理解它,我在F2Py forum thread上找到答案。添加integer py_func通過!f2py前綴)不招對我來說:

subroutine test(py_func) 

use iso_fortran_env, only stdout => output_unit 

!f2py intent(callback) py_func 
external py_func 
integer py_func 
!f2py integer y,x 
!f2py y = py_func(x) 

integer :: a 
integer :: b 

a = 12 
write(stdout, *) a 

b = py_func(a) 
write(stdout, *) b 

end subroutine 

也許這是被需要用於存儲分配給B之前結果的臨時值的空間呢?在任何情況下,它顯然都是依賴於編譯器的,這就解釋了爲什麼它不在您可以在網上其他地方找到的各種F2Py回調示例中。

+2

你的文件中沒有'implicit none',因此'py_func'由於隱式的輸入規則而被認爲是「真實的」。 –

相關問題