![](/img/trans.png)
[英]External function ‘f’ at (1) has no IMPLICIT type in subroutine with f2py
[英]How make external function work with f2py?
我正在嘗試用f2py
編譯一段舊的 Fortran 代碼,以便可以在 Python 中調用它。 但是,有一部分涉及外部功能不起作用。 這是一個最小的工作示例,首先是test.f
:
function f(x)
implicit double precision (a-z)
f = x * x
return
end function f
subroutine gauss(fun)
implicit double precision (a-h, j-z)
! external fun
x = 1.5
write(*,*) fun(x)
return
end subroutine gauss
並用makefile
編譯后
f2py -c --quiet --fcompiler=gnu95 \
--f90flags=“-Wtabs” \
-m test \
test.f
我使用 Python 從 Python 調用它
import test
f = lambda x: x
test.gauss(test.f)
並得到錯誤TypeError: test.gauss() 1st argument (fun) can't be converted to double
。
在第二次嘗試中,我取消注釋子例程gauss
中的行external fun
並在編譯期間收到以下錯誤消息
/tmp/tmpet9sk3e9/src.linux-x86_64-3.7/testmodule.c: In function ‘cb_fun_in_gauss__user__routines’:
/tmp/tmpet9sk3e9/src.linux-x86_64-3.7/testmodule.c:313:8: error: variable or field ‘return_value’ declared void
我現在沒有想法,任何幫助將不勝感激!
我已經(部分)想通了: f2py
需要你明確指定函數的使用。 方法如下:
function f(x)
implicit double precision (a-z)
f = x * x
return
end function f
subroutine gauss(fun)
implicit double precision (a-h, j-z)
!! <-------- updates starts HERE
external fun
!f2py real*8 y
!f2py y = fun(y)
double precision fun
!! <-------- updates ends HERE
x = 1.5
write(*,*) fun(x)
return
end subroutine gauss
然后使用編譯它
main:
f2py -c --quiet --fcompiler=gnu95 \
--f90flags=“-Wtabs” \
-m test \
test.f
你可以用
import test
f = lambda x: x
test.gauss(test.f)
test.gauss(f)
並看到外部函數適用於 Fortran 和 Python 函數。
兩個旁注:
!f2py intent(callback) fun
是必要的,但我發現代碼可以在沒有它的情況下工作。y
(盡管這可能不是一個好習慣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.