从python中的共享fortran库调用函数 [英] call functions from a shared fortran library in python

查看:439
本文介绍了从python中的共享fortran库调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Python中的Fortran共享库中调用一些函数。我在网上找到了一些链接并阅读它们,根据我发现的,我应该这样做:

  libadd = cdll.LoadLibrary ('./libbin.so')

来加载共享对象。但是,此共享对象包含来自另一个共享库的一些符号。我阅读了cdll的帮助,但似乎无法同时加载多个共享对象文件。如何从Fortran库调用函数,这很可能是由英特尔Fortran编译器编译的?

解决方案

您需要了解共享对象中函数的签名。你有源代码,或者一些参考文件来解释函数名称和参数类型吗?

例如,我有这个源代码( mult.f90 ):

 整数函数multiply(a,b)
整数,意图(in):: a ,b
乘法= a * b
结束函数乘法

...和为了演示如何一次加载和使用多个共享对象,我还有( add.f90 ):

 整数函数addtwo(a,b)
整数,意图(in):: a,b
addtwo = a + b
结束函数addtwo

%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_

注意共享对象中的符号名称附有下划线。因为我有源码,所以我知道签名是 multiply_(int * a,int * b),所以很容易从 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))

输出:

  8 
6


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

libadd = cdll.LoadLibrary('./libbin.so') 

to load the shared object. However, this shared object includes some symbols from another shared library. I read the help of cdll however it does not seem possible to load several shared object files at the same time. How may I call functions from this Fortran library, which is most probably compiled by the Intel Fortran compiler?

解决方案

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

这篇关于从python中的共享fortran库调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆