Re: [f2py] Python Call Back in Fortran

Pearu Peterson <[email protected]> Sun, 6 Feb 2011 08:26:07 +0200
Newsgroups gmane.comp.python.f2py.user
Message-ID <[email protected]>
Hi,

Here follows an example that illustrates how to handle this usage case:

!foo.f90:
subroutine sub1(python_callback)

  !f2py intent(callback) python_callback
  external python_callback

  !f2py call python_callback(0,0,0) !define python_callback signature
  call sub2(1,2,3)

end subroutine sub1

subroutine sub2(arg1,arg2,arg3)
  integer arg1, arg2, arg3
  external python_callback
  call python_callback(arg1,arg2,arg3)

end subroutine sub2
!eof

f2py -c -m ex foo.f90

>>> def cb(arg1, arg2, arg3):
...     print 'calling python cb(%s, %s, %s)' % (arg1, arg2, arg3)
...
...
>>> import ex
>>> ex.sub1(cb)
calling python cb(1, 2, 3)

HTH,
Pearu

On Sun, Feb 6, 2011 at 1:11 AM, Gaetan Kenway <kenway-kBRAJjP0/PtSpjfjxSPG1fd9D2ou9A/[email protected]>wrote:

> Hello
>
> I have a question about python callbacks in Fortran. I've been able to
> setup simple python call backs with no issue. The problem I'm having is I
> need a way to "store" the call back function handle in Fortran. I need to
> call the python callback from a Fortran function that I can't explicitly
> pass the python function handle to .  I need to have something like below.
> Subroutine sub1 is wrapped and sub2 has a fixed form that is actually called
> from and internal PETSc function and I can't change the sequence of
> arguments.
>
> subroutine sub1(python_callback)
>
>     external python_callback
>
> end subroutine sub1
>
> subroutine sub2(arg1,arg2,arg3)
>
> external python_callback
> ! I want to call python_callback here
>     call python_callback(arg1,arg2,arg3)
>
> end subroutine sub2
>
> It would be nice if you could just put the callback into a module and make
> that available in sub2. Is this possible in fortran? The code as above
> compiles, but when you try to import it into Python, python complains that
> python_callback is not defined. Is there a way to trick the compiler into
> using the callback defined in the pyf file?  Is there some way of telling
> f2py with an intent(callback) that the external python_callback in sub2 is
> actually defined as python callback?
>
> If anyone has any suggestions or know this is entirely impossible in
> fortran it would be greatly appreciated.
>
> Gaetan Kenway
>
> _______________________________________________
> f2py-users mailing list
> f2py-users-Y4l6ocDipWCuvFJfX82//[email protected]
> http://cens.ioc.ee/mailman/listinfo/f2py-users
>
>

_______________________________________________
f2py-users mailing list
f2py-users-Y4l6ocDipWCuvFJfX82//[email protected]
http://cens.ioc.ee/mailman/listinfo/f2py-users