callback Python from Fortran

試著忘記壹切 提交于 2019-12-06 04:48:40

问题


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`

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




回答2:


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


来源:https://stackoverflow.com/questions/17198642/callback-python-from-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!