Using via scikit-build
scikit-build provides two separate concepts geared towards the users of Python extension modules.
A
setuptoolsreplacement (legacy behaviour)A series of
cmakemodules with definitions which help building Python extensions
scikit-build provides two separate concepts geared towards the users of Python extension modules.
A setuptools replacement (legacy behaviour)
A series of cmake modules with definitions which help building Python extensions
f2py
-cnumpy.distutilsFor situations where no setuptools replacements are required or wanted (i.e.
if wheels are not needed), it is recommended to instead use the vanilla
cmake setup described in Using via cmake.
We will consider the fib example from Three ways to wrap - getting started section.
C FILE: FIB1.F
SUBROUTINE FIB(A,N)
C
C CALCULATE FIRST N FIBONACCI NUMBERS
C
INTEGER N
REAL*8 A(N)
DO I=1,N
IF (I.EQ.1) THEN
A(I) = 0.0D0
ELSEIF (I.EQ.2) THEN
A(I) = 1.0D0
ELSE
A(I) = A(I-1) + A(I-2)
ENDIF
ENDDO
END
C END FILE FIB1.F
CMake modules onlyConsider using the following CMakeLists.txt.
### setup project ###
cmake_minimum_required(VERSION 3.9)
project(fibby
VERSION 1.0
DESCRIPTION "FIB module"
LANGUAGES C Fortran
)
# Safety net
if(PROJECT_SOURCE_DIR
setuptools replacementThe utility of scikit-build lies in being able to drive the generation of
more than extension modules, in particular a common usage pattern is the
generation of Python distributables (for example for PyPI).
The workflow with scikit-build straightforwardly supports such packaging requirements. Consider augmenting the project with a setup.py as defined:
from
Much of the logic is the same as in Using via cmake, however notably here the
appropriate module suffix is generated via sysconfig.get_config_var("SO").
The resulting extension can be built and loaded in the standard workflow.
ls .
# CMakeLists.txt fib1.f
cmake -S . -B build
cmake --build build
cd build
python -c "import numpy as np; import fibby; a = np.zeros(9); fibby.fib(a); print (a)"
# [ 0. 1. 1. 2. 3. 5. 8. 13. 21.]
Along with a commensurate pyproject.toml
[build-system]
requires = ["setuptools>=42", "wheel", "scikit-build", "cmake>=3.9", "numpy>=1.21"]
build-backend = "setuptools.build_meta"
Together these can build the extension using cmake in tandem with other
standard setuptools outputs. Running cmake through setup.py is
mostly used when it is necessary to integrate with extension modules not built
with cmake.
ls .
# CMakeLists.txt fib1.f pyproject.toml setup.py
python setup.py build_ext --inplace
python -c "import numpy as np; import fibby.fibby; a = np.zeros(9); fibby.fibby.fib(a); print (a)"
# [ 0. 1. 1. 2. 3. 5. 8. 13. 21.]
Where we have modified the path to the module as --inplace places the
extension module in a subfolder.