[f2py] call-back arguments

Pearu Peterson pearu@cens.ioc.ee
Sun, 22 Jul 2001 23:53:49 +0200 (EET)


On Sun, 23 Jul 2001, Martin wrote:

> How can I get rid of Fortranish arguments (like array dimensions) in 
> call-backs?

By defining them optional. See below.

> If the wrapped Fortran function expects a call-back cb_f with signature, say:
> 
> call cb_f (x, a, m, n)
> double dimension(m) intent(out) :: x
> double dimension(m,n) intent(in) :: a
> integer :: m
> integer :: n
> 
> Can I interface to a Python function cb_py like
> 
> x = cb_py (a)
> ...
> 
> or a similar one?

Yes. See below.

> What would the signature file look like?

Here follows an example:

1) File test.f
      subroutine foo (cb_f,a,m,n)
      external cb_f
      integer n,m
      real*8 x(m),a(m,n)
      call cb_f(x,a,m,n)
      print*, x
      end
2) Run
	f2py test.f -m cb -h cb.pyf

3) Modify the signature of cb_f in cb.pyf:
<snip>
        subroutine cb_f(x,a,m,n) ! in :cb:test.f:foo:unknown_interface
            real*8 dimension(m),intent(out) :: x
            real*8 dimension(m,n),intent(in) :: a
            integer optional,check(shape(a,1)==m),depend(a) :: m=shape(a,1)
            integer optional,check(shape(a,0)==n),depend(a) :: n=shape(a,0)
        end subroutine cb_f
<snip>

4) Run
	make -f Makefile-cb

5) In Python:

>>> def cb_py(a): # return first row of a
...  return a[0]
... 
>>> from Numeric import *
>>> a = ones((3,4))
>>> a[:,1]=3
>>> a[0,0]=2
>>> a
array([[2, 3, 1, 1],
       [1, 3, 1, 1],
       [1, 3, 1, 1]])
>>> import cb
>>> cb.foo(cb_py,a)
 x=  2.  3.  1.  1.
>>>

Regards,
	Pearu