5

Now I am using the f2py to call Python function from Fortran code. I have tried a very easy example but it didn't work.

Fortran90 code:

subroutine foo(fun,r)
external fun
integer ( kind = 4 ) i
real ( kind = 8 ) r
r=0.0D+00
do i= 1,5
    r=r+fun(i)
enddo
end

using the commandline:

f2py -c -m callback callback.f90

Python code:

import callback

def f(i):
    return i * i
print callback.foo(f)

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: `Required argument 'r' (pos 2) not found`
john_science
  • 6,325
  • 6
  • 43
  • 60
lbjx
  • 195
  • 1
  • 3
  • 12
  • 1
    I'm no python expert, but doesn't the error suggest that two arguments are necessary? – Kyle Kanos Jun 19 '13 at 23:34
  • Hi, I have solved the problem. The thing that I was faced with was not another argument that was needed. I was trying another .pyf using the commend line to auto generated and decide which argument should be an input value and which should be an output value. Then, The problem is when I call the function the type of the arguements are not the same. So I fixed r to be an integer and the problem solved. – lbjx Jun 20 '13 at 06:45

2 Answers2

1

You need to declare r as a return value... this is good Fortran 90 practice anyway. Right now f2py is assuming it is an input value.

subroutine foo(fun,r)
    external fun
    real ( kind = 8 ), intent(out) :: r
    integer ( kind = 4 )           :: i
    r=0.0D+00
    do i= 1,5
        r=r+fun(i)
    enddo
end

f2py uses Fortran's intent directives to determine what is passed to the function and what is returned.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
0

python:

# -*- coding: utf-8 -*-
import MArray

print MArray.__doc__
print MArray.s1dim_array.__doc__
print MArray.s2dim_array.__doc__

print "="*60
print help(MArray)
print "="*60
print help(MArray.s1dim_array)


print "="*60
MArray.s1dim_array([6.,7.,8.])


print "="*60
MArray.s2dim_array([[6.,7.,8.],[1,2,3]])




subroutine S1dim_Array (iN_dim, rArray)
  implicit none  
  integer,  intent(in) :: iN_dim
  real,     intent(in) :: rArray(iN_dim)
  print*, iN_dim
  print*, rArray
  Return
End subroutine


subroutine S2dim_Array (iN_Row, iN_Col, rArray)
  implicit none  
  integer,  intent(in) :: iN_Row, iN_Col
  real,     intent(in) :: rArray(iN_Row, iN_Col)
  integer :: i , j
  print*, iN_Row, iN_Col
  do i = 1 , iN_Row
    write(*,*) (rArray(i,j), j = 1,iN_Col)
  enddo
  Return
End subroutine
  • sorry, I didnt get the idea. The problem is that I try to first call the fortran code from python and then call the python funtion from fortran. There should be an external part in fortran – lbjx Jun 20 '13 at 06:47