python调用函数库,从python中的共享fortran库调用函数

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值