5

现在我正在使用f2py从 Fortran 代码调用 Python 函数。我尝试了一个非常简单的示例,但没有成功。

Fortran90 代码:

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

使用命令行:

f2py -c -m 回调 callback.f90

Python代码:

import callback

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

错误:

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

2 回答 2

1

您需要声明r为返回值……无论如何,这都是 Fortran 90 的良好做法。现在f2py假设它是一个输入值。

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使用 Fortran 的意图指令来确定传递给函数的内容和返回的内容。

于 2013-06-20T03:11:26.660 回答
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
于 2013-06-20T03:40:11.117 回答