A minimal example of wrapping c++ code with python using NanoBind. The python project shall only use pyproject.toml and will use scikit-build-core as a build system.
The example should cover the following:
- Minimal C++ code example
- Minimal Python wrapper example using
NanoBind
- Minimal
pyproject.toml
file - Minimal
CMakeLists.txt
file - Build system using
scikit-build-core
- Build and test code in a
mambabuild
package compilation (so that it can easily be uploaded to conda)
First install the pre-requisites for nanobind
and scikit-build-core
build requirements from conda-forge.
mamba env update -f environment.build.yml --prune
If you are using CLION and want to get type hints from the c++ packages in your conda environment, I recommend creating a batch files to set the environment variables and use that as an environment file. See Build, Execution, Deployment > Toolchains -> Add Environment -> Environment file.
Here is an example of a setup.bat
file that I use to set the environment variables for CLION.
@echo off
:: mamba env update -f environment.build.yml --prune
:: mamba activate nano-min
set MY_PY_VER=311
set PREFIX=c:/mambaforge/envs/nano-min
set LIBRARY_PREFIX=%PREFIX%/Library
set CMAKE_PREFIX_PATH=%PREFIX%;%LIBRARY_PREFIX%/include;%LIBRARY_PREFIX%/lib;%LIBRARY_PREFIX%/bin
set OpenCASCADE_DIR=%LIBRARY_PREFIX%/lib/cmake/opencascade
set OpenCASCADE_INCLUDE_DIR=%LIBRARY_PREFIX%/include/opencascade
set PYTHON_EXECUTABLE=%PREFIX%/python.exe
set PYTHON_LIBRARY=%PREFIX%/libs/python%MY_PY_VER%.lib
Now you are ready to write some c++ code and wrap it with python.
Open a terminal and navigate to the root directory.
Activate the nano-min
environment (ie. mamba activate nano-min
) and install the package using the following command.
pip install --no-build-isolation . -v
This will install the package into the nano-min
environment and you can use it as you would any other python package.
import my_ext
res = ext.add(1, 2)
print(res)
Open a terminal and navigate to the root directory.
Activate the nano-min
environment (ie. mamba activate nano-min
) and compile the conda package
using the following command.
mamba mambabuild conda -c conda-forge --python 3.11 --override-channels
mamba install --use-local nano-min
- If the python stubs are not updated in your IDE during development try uninstalling and reinstalling the package.