Ryan Garland Ryan Garland - 3 months ago 7x
Python Question

Can I use F2PY on a subroutine with subroutine calls?

Using F2PY as a wrapper, is it possible to use subroutines with subroutine calls? And if so, how?

In case I am unclear, I mean like this:

SUBROUTINE average(a, b, out)

real a, b, out
cf2py intent(in) a, b
cf2py intent(out) out

call add(a, b, out)



The add subroutine is as follows:

subroutine add(a, b, out)

real a, b, out

out = a + b


Trying f2py -c -m average average.f and importing to python I get:

ImportError: ./average.so: undefined symbol: add_

Also, adding intents to the second subroutine does not fix the issue.


You need to include the file containing add in your compile command, e.g.

f2py -c -m average average.f add.f

The shared library you import needs to have its references resolved at import time, which means they need to be either contained in the library or linked to it. You can accomplish keeping your functions in separate libraries like this:

gfortran -shared -fPIC -o add.so add.f
f2py -c -m average average.f add.so

which will produce a python module that does not itself contain add but will have a runtime link dependency on add.so for the function.