I have been attempting to call a simple Fortran subroutine from python using f2py without success. The Fortran subroutine just adds two numbers defined in the python code. The Fortran code is:
C
SUBROUTINE TESTLIB(A,B,C)
C
REAL, intent (in) :: A, B
REAL, intent (out) :: C
C = A + B
END SUBROUTINE TESTLIB
Python:
import numpy as np
import testlib2
A = 3
B = 2
C = testlib2.testlib(A, B)
print("C = ", C)
I created testlib2.pyd file from the command line with
python -m numpy.f2py -c -m testlib2 testlib2.f
Then placed testlib2.pyd
file in the same directory as the python file (testlib.py). I had to install meson, ninja, cmake, charset-normalizer and pkgconfig libraries to make F2py work with Python 3.12.
When I run the python code testlib.py (Spyder 5.5) I receive the following error:
File c:usersbcndocumentshpshps fortrantestlib.py:6
C = testlib2.testlib(A, B)
TypeError: testlib2.testlib() missing required argument 'c' (pos 3).
The call to the Fortran subroutine appears to requiring the C variable to be defined but has been defined as an “out” variable. Not sure why it is doing this. The examples I have seen indicate that the Fortran subroutine needs to have the out variable listed. Using Windows 11 and Python 3.12. Any help would be appreciated. Thanks.
2
The signature of the Fortran code and that used by the python code should be the same. You are specifying a procedure with one return value. The equivalent in python would be
testlib2.testlib(A, B, C)
In python, unless you’re dealing with objects, the parameters do not change. The intent is always IN. To make the signatures the same, change testlib to a function
C
REAL FUNCTION TESTLIB(A,B)
C
REAL, intent (in) :: A, B
TESTLIB = A + B
END FUNCTION TESTLIB
1