共計 672 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 可以通過使用 ctypes
庫來調用 Fortran 方法。
下面是一個簡單的例子,展示了如何在 Python 中調用 Fortran 方法:
-
首先,需要編寫一個 Fortran 程序,并將其編譯為共享庫文件(例如,
.so
文件)。! example.f90 subroutine add(a, b, c) integer, intent(in) :: a, b integer, intent(out) :: c c = a + b end subroutine add
-
使用 Fortran 編譯器(例如 gfortran)將 Fortran 程序編譯為共享庫文件。
$ gfortran -shared -o example.so example.f90
-
在 Python 中使用
ctypes
庫加載共享庫,并調用其中的 Fortran 方法。import ctypes # 加載共享庫 example = ctypes.CDLL('./example.so') # 定義 Fortran 方法的參數和返回類型 example.add.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)) example.add.restype = None # 調用 Fortran 方法 a = 2 b = 3 c = ctypes.c_int() example.add(a, b, ctypes.byref(c)) print(c.value) # 輸出結果為 5
通過 ctypes
庫,可以將 Fortran 方法聲明為 Python 函數,并通過調用這些函數來使用 Fortran 代碼。
丸趣 TV 網 – 提供最優質的資源集合!
正文完