call functions from a shared fortran library in python

前端 未结 3 1334
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 15:19

I would like to call some functions from a Fortran shared library in Python. I have found some links on the net and read them, and according what I found, I should do

<
3条回答
  •  北海茫月
    2020-12-23 15:55

    You'll need to know the signatures of the functions in the shared object. Do you have the source code, or some reference which explains the function names and argument types?

    For example, I have this source code (mult.f90):

    integer function multiply(a, b)
        integer, intent(in) :: a, b
        multiply = a * b
    end function multiply
    

    .. and to demonstrate how you can load and use multiple shared objects at once, I also have (add.f90):

    integer function addtwo(a, b)
        integer, intent(in) :: a, b
        addtwo = a + b
    end function addtwo
    

    Compile, examine symbols:

    % gfortran-4.4 -shared -fPIC -g -o mult.so mult.f90
    % gfortran-4.4 -shared -fPIC -g -o add.so add.f90
    % nm -ao mult.so | grep multiply
    mult.so:00000000000005cc T multiply_
    

    Notice the symbol name in the shared object has an underscore appended. Since I have the source, I know that the signature is multiply_(int *a, int *b), so it is easy to invoke that function from ctypes:

    from ctypes import byref, cdll, c_int
    
    mult = cdll.LoadLibrary('./mult.so')
    add = cdll.LoadLibrary('./add.so')
    a = c_int(2)
    b = c_int(4)
    print mult.multiply_(byref(a), byref(b))
    print add.addtwo_(byref(a), byref(b))
    

    Output:

    8
    6
    

提交回复
热议问题