Python Callback from Fortran

Now I use f2pyto call Python functions from Fortran code. I tried a very simple example, but that 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 command line:

f2py -c -m callback callback.f90

Python Code:

import callback

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

Mistake:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: `Required argument 'r' (pos 2) not found`
+3
source share
2 answers

You need to declare it ras a return value ... that's good, Fortran 90 doesn't care. Right now f2pyassumes this 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 intent directives to determine what is passed to the function and what is returned.

0
source

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
0
source

Source: https://habr.com/ru/post/1620879/


All Articles