Ryan Garland
Ryan Garland

Reputation: 65

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)

    out=out/2

    END

The add subroutine is as follows:

  subroutine add(a, b, out)

  real a, b, out

  out = a + b

  return
  end

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.

Upvotes: 5

Views: 2221

Answers (2)

SMISA16
SMISA16

Reputation: 11

You guys already figured, but just to build on to casey's response: If you run into a situation where you want to avoid having to compile add.f over again each time you modify average.f, you can use the static library, this way you don't have to make a link to LD_LIBRARY_PATH:

$ gfortran -c add.f
$ f2py -c -m average average.f add.o

The first command above will generate the static object (library) file. Second one used that object file to compile your final subroutine for python.

Upvotes: 0

casey
casey

Reputation: 6915

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.

Upvotes: 6

Related Questions