4

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

5
  • Why aren't you using the Fortran FFI stuff that comes with NumPy? Commented Mar 26, 2012 at 3:57
  • You mean f2py? It's causing a lot of headaches on my system and I decided this would be a good short-term fix. In theory! Commented Mar 26, 2012 at 3:59
  • 1
    you could try addtwo = real(a+b), does it fix it? Commented Mar 26, 2012 at 4:00
  • that does, but implemented into main code (see edit), and I'm still not getting the expected result. I can't see any difference between those two functions, though. Commented Mar 26, 2012 at 4:16
  • 1
    this looks interesting docs.python.org/library/ctypes.html#return-types Commented Mar 26, 2012 at 4:26

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.