python fortran混编 ctypes,使用ctypes从Python调用fortran函数

I am looking to use ctypes to call some old fortran libraries which were written by my boss a few years ago. I followed the example given in this previous question, and I get the results as expected.

However, when I modify the code, to get slightly closer to the situation I face, so that

integer function addtwo(a, b)

integer, intent(in) :: a, b

addtwo = a + b

end function

becomes

real function addtwo(a, b)

integer, intent(in) :: a, b

addtwo = a + b

end function

i.e., the function is now real, not integer, the value returned is always 0. Can anyone explain what's going on and how I should get around this?

(PS. I'm using a 64-bit gfortran compiler on mac os snow leopard)

EDIT: The function I'm struggling with looks like:

real function ykr(seed)

integer, intent(in) :: seed

real ykr0

ykr= real(seed)

end function

Really, ykr calls another function, ykr0, recursively, but since I'm struggling even with this basic aspect I'm ignoring that for now. I can't see what's different between this code and the above, but calling ykr_(byref(c_int(4))) returns 0, not 4 as expected...

解决方案

Add the line

ykr_.restype = c_float

in your python code, before ykr_(byref(c_int(4))).

This sets the return type for the function to float (or real in Fortan language).

In the original post, this was not necessary since int was assumed as default.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值