Call fortran function from Python with ctypes

sam*_*b8s 4 python fortran ctypes

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
Run Code Online (Sandbox Code Playgroud)

becomes

real function addtwo(a, b)
  integer, intent(in) :: a, b
  addtwo = a + b
end function
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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...

Kys*_*Tao 5

添加行

ykr_.restype = c_float
Run Code Online (Sandbox Code Playgroud)

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

在原始帖子中,这没有必要,因为int被假定为默认值。