Calling Fortran from Python with ctypes
Python can call a C library without a compiler, a header or a build step, through the ctypes module of the standard library. A Fortran subroutine with bind(c) is such a library once it is compiled as a shared object, so the previous lesson's subroutine is callable from a script in three lines and a description of its arguments. This lesson builds the library, writes the script, calls both procedures and shows the two mistakes a first attempt usually makes.
The shared library
-shared asks for a shared object instead of an executable and -fPIC makes the code position independent, which a shared object has to be. The result is a file libstats.so that a program can load at run time, and the two procedures in it are the ones a C program called in lesson 106.
The file stats.f90:
subroutine stats(x, n, mean, sd) bind(c, name="stats")
use, intrinsic :: iso_c_binding
implicit none
integer(c_int), value :: n
real(c_double), intent(in) :: x(n)
real(c_double), intent(out) :: mean, sd
integer :: i
mean = 0.0_c_double
do i = 1, n
mean = mean + x(i)
end do
mean = mean / real(n, c_double)
sd = 0.0_c_double
do i = 1, n
sd = sd + (x(i) - mean) ** 2
end do
sd = sqrt(sd / real(n - 1, c_double))
end subroutine stats
function hyp(a, b) bind(c, name="hyp") result(y)
use, intrinsic :: iso_c_binding
implicit none
real(c_double), value :: a, b
real(c_double) :: y
y = sqrt(a * a + b * b)
end function hyp
gfortran -Wall -Wextra -std=f2018 -shared -fPIC stats.f90 -o libstats.so
ls -l libstats.so
-rwxr-xr-x 1 agent agent 16264 Nov 18 19:14 libstats.so
The Python script
ctypes.CDLL("./libstats.so") loads the file, and the attributes of the object are the symbols in it. The rest of the script describes each function: the argument types in order, and the type of the result. With that description ctypes converts Python values to C ones and back.
The file call_stats.py:
import ctypes lib = ctypes.CDLL("./libstats.so") lib.stats.argtypes = [ ctypes.POINTER(ctypes.c_double), ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ] lib.stats.restype = None values = (ctypes.c_double * 5)(2.0, 4.0, 4.0, 4.0, 9.0) mean = ctypes.c_double() sd = ctypes.c_double() lib.stats(values, 5, ctypes.byref(mean), ctypes.byref(sd)) print(f"mean = {mean.value:.4f} sd = {sd.value:.4f}") lib.hyp.argtypes = [ctypes.c_double, ctypes.c_double] lib.hyp.restype = ctypes.c_double print(f"hyp(3, 4) = {lib.hyp(3.0, 4.0):.4f}")
python3 call_stats.py
mean = 4.6000 sd = 2.6077
hyp(3, 4) = 5.0000
Python 3.14.10 here, and the two lines are the same numbers the C main printed: the interface does not care which language is on the other side, only that the description matches the symbol. The subroutine returns nothing, so its restype is None; the function returns a double, so its restype is c_double.
ARGTYPES and RESTYPE
argtypes is a list with one entry per C parameter, and it is the Python side of the interface block on the Fortran side. A pointer to double is ctypes.POINTER(ctypes.c_double), an int is ctypes.c_int, and a parameter passed by value is the plain type. A Fortran dummy without value is a pointer here, exactly as it was a pointer in the C declaration.
restype describes what the function returns, and a subroutine returns nothing: None. A function that returns a double needs c_double, and this is the declaration a first attempt forgets, because ctypes works without it and gives a wrong answer rather than an error.
An array through ctypes
(ctypes.c_double * 5)(2.0, ...) builds a C array of five doubles, and ctypes passes it as a pointer because that is what a C array is. The length is the second argument, the same one Fortran uses as the bound. ctypes.byref(mean) passes the address of the scalar, which is what an intent(out) dummy expects.
The array keeps its Python identity: the script can read values[0] after the call and see what Fortran did to it. That is the cheapest way to pass a large buffer to a Fortran routine from Python without a copy, and it is the reason a scientific Python program that needs speed keeps its inner loop in a library like this one.
The trap: no RESTYPE
Without restype ctypes assumes the function returns an int. Called that way, hyp(3.0, 4.0) prints:
import ctypes lib = ctypes.CDLL("./libstats.so") lib.hyp.argtypes = [ctypes.c_double, ctypes.c_double] print(lib.hyp(3.0, 4.0)) print(type(lib.hyp(3.0, 4.0)))
2
<class 'int'>
The two is not the answer and not a rounded one: it is whatever happened to be in the integer register when the function returned, because the double came back in a floating-point register that ctypes never read. Nothing raises an exception, the type is a plain int, and a program that goes on to use the number produces a wrong result a long way from the call.
The rule that follows is short: describe every function completely, argtypes and restype both, and test the first call against a value computed in Python. A ctypes binding without a restype is a binding with a guess in it.
The library is not found
A path that does not exist is the other first error, and Python reports it as an OSError from the loader:
python3 bad_path.py
Traceback (most recent call last):
File "/tmp/w107/other/bad_path.py", line 3, in <module>
lib = ctypes.CDLL("./libstats.so")
File "/usr/lib/python3.14/ctypes/__init__.py", line 433, in __init__
self._handle = self._load_library(name, mode, handle, winmode)
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.14/ctypes/__init__.py", line 475, in _load_library
return _dlopen(name, mode)
OSError: Error loading shared library ./libstats.so: No such file or directory
The last line is the useful one, and the path in it is the one the script wrote, not a search path: ctypes.CDLL with a relative name resolves against the working directory, so a script started from another directory fails even though the library exists next to it. An absolute path built from __file__ is the fix, and it is what a script that ships with its library should do.
Rules for the Python side
Describe every function with both argtypes and restype. Build the shared library with -shared -fPIC and export only what the script calls, which means bind(c, name=...) on every procedure. Load the library by an absolute path derived from the script. And keep a test that compares the first result with a Python computation, because every other check in the pipeline trusts the binding.
f2py, the tool that generates such a binding from Fortran source, is not in this image and lesson 109 explains what it would do. The ctypes route on this page needs nothing but the standard library and a compiler, which is why it is the one shown.
Exercises
- Call stats with a Python list instead of a ctypes array. What does ctypes do, and why is the result not what you want?
- Add a bind(c) function that returns an integer and call it with the right restype. Which ctypes type is it?
- Change the library path to an absolute one built from os.path.dirname(__file__) and run the script from another directory. Does it work?
- Print values[0] after the call to stats. Did Fortran change the array?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What builds a shared library from a Fortran file?
Answer
gfortran -shared -fPIC stats.f90 -o libstats.so
-shared makes the object, -fPIC makes it position independent.
-
What does
ctypes.CDLLdo?Answer
Loads a shared library and gives access to its symbols
The attributes of the object are the exported symbols.
-
What does
restype = Nonemean?Answer
The function returns nothing, as a subroutine does
A Fortran subroutine has no result value.
-
What does ctypes do when RESTYPE is missing?
Answer
Assumes an int and returns something meaningless for a double
The double comes back in a register ctypes never reads.
-
How is a ctypes array of five doubles built?
Answer
(ctypes.c_double * 5)(2.0, 4.0, 4.0, 4.0, 9.0)
The multiplication builds the array type, the call fills it.
-
What does
ctypes.byref(mean)pass?Answer
The address of the scalar, as an intent(out) dummy expects
Fortran writes through the address.
-
Why does a relative library path fail?
Answer
It is resolved against the working directory, not the script
Build the path from __file__.
-
Why is the first call compared with a Python computation?
Answer
Every other check trusts the binding, so the binding is what to test
A wrong restype gives a plausible number.
-
Which tool would generate this binding from Fortran source?
Answer
f2py, which is not in this image
Lesson 109 explains what it does and why it is not run here.
-
What does a Fortran dummy without VALUE match on the Python side?
Answer
A pointer type in argtypes
The dummy is passed by reference.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev