Fortranで作成したdylibをPythonで呼び出す

既存のFortran資産をPythonから利用する手段として有効です。
以下はFortranで作成したヘロンの公式のサブルーチンをPythonから使用する例です。

環境は以下のとおりです。

OS
 macOS 10.13.6
fortran コンパイラ
 GNU Fortran (GCC) 4.9.2 20141029 (prerelease)
python
 Python 3.7.3

Fortranサブルーチンは以下です。

subroutine heron(a,b,c,s)
    implicit none
    real(8),intent(in) :: a,b,c
    real(8),intent(out):: s
    real(8) ss
    ss = (a+b+c)/2.0
    s = sqrt(ss*(ss-a)*(ss-b)*(ss-c))
end subroutine

gfortranによるコンパイルは以下のとおりです。

gfortran -shared -fPIC -o heron.dylib heron.f90

実行するPythonは以下です。

from ctypes import * 

heron = cdll.LoadLibrary("heron.dylib")

heron.heron_.argtypes = [POINTER(c_double),POINTER(c_double),POINTER(c_double),POINTER(c_double)]
heron.heron_.restype = c_void_p  

a = 3.0
b = 4.0
c = 5.0
s = 0.0
a = c_double(a)
b = c_double(b)
c = c_double(c)
s = c_double(s)
 
heron.heron_(byref(a),byref(b),byref(c),byref(s)) 
print(s.value)

戻り値の引数、s は Python 側で予め宣言しておかないと「not defined」になるので、とりあえず 0.0 を代入しています。(Fortran側でFunctionにすれば良いのですが、gfortanでは上手くいかず)

上記はアーキテクチャやFortranコンパイラによって書き方が異なるのでご注意ください。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA