使用ctypes从Python调用fortran函数 [英] Call fortran function from Python with ctypes

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

问题描述

我正在寻找使用ctypes来呼叫几年前由我的老板编写的一些旧的fortran库。我遵循上一个问题给出的示例,我得到了预期的结果。

但是,当我修改代码时,要稍微接近我面对的情况,以便

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

变成

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

即函数现在 real ,而不是 integer ,返回的值总是 0 。任何人都可以解释发生了什么以及我应该如何解决这个问题?


$ b

(PS。我在mac os snow leopard上使用64位gfortran编译器) p>

编辑:我挣扎的功能看起来像:

 真实函数ykr(种子)

整数,意图(in):: seed
real ykr0
ykr = real(种子)
结束函数

真的, ykr 调用另一个函数, ykr0 ,但是由于即使在这个基本方面我仍然在挣扎,所以我暂时忽略了这一点。我看不出这段代码和上面的代码有什么不同,但调用 ykr_(byref(c_int(4)))返回 0 ,而不是 4 和预期的一样...

解决方案

添加行

  ykr_.restype = c_float 

在你的python代码中,在 ykr_(byref(c_int(4)))之前。
这将函数的返回类型设置为 float (或Fortan语言中的 real )。 p>

在原始文章中,这并不是必须的,因为int被假定为默认值。


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.

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

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