This project demonstrates how to use Cython to wrap a C++ algorithm, enabling parameter access and modification using Python keyword arguments. This example can be used as a reference for improving parameter accessibility in PyOpenMS.
- Wraps a C++ class using Cython.
- Allows setting and retrieving parameters via Python keyword arguments.
- Provides a simple setup for compiling the C++ code and using it in Python.
Ensure you have the following installed:
- Python 3.8 or later
- Cython
- A C++ compiler (e.g., MSVC on Windows, g++ on Linux/Mac)
Cython-example/
│── src/
│ │── cpp/
│ │ │── algorithm.h # C++ header file defining the class
│ │ │── algorithm.cpp # C++ implementation file
│ │── cython/
│ │ │── algorithm.pxd # Cython header file
│ │ │── algorithm.pyx # Cython wrapper file
│ │── setup.py # Build script for Cython
│ │── test.py # Python script to test the wrapped C++ class
- Clone the repository:
git clone https://github.com/yourusername/Cython-example.git cd Cython-example/src - Install dependencies:
pip install cython
- Compile the Cython module:
python setup.py build_ext --inplace
Run the test script to see the algorithm in action:
python test.pyExpected output:
Initial parameters: {'param1': 20.0, 'param2': 10, 'param3': True}
Updated parameters: {'param1': 5.0, 'param2': 10, 'param3': False}
Computation result: 15.0
algo2 parameters: {'param1': 210.0, 'param2': 100, 'param3': True}
Computation result: 21000.0
algo3 parameters: {'param1': 210.0, 'param2': 5, 'param3': True}
Computation result: 1050.0Update test.py to try different examples.
- cpp/algorithm.h & cpp/algorithm.cpp: Define the C++ class with multiple parameters.
- cython/algorithm.pxd & cython/algorithm.pyx: The Cython wrapper that exposes the C++ class to Python.
- setup.py: Compiles the C++ and Cython files into a Python module.
- test.py: Runs a simple test to verify functionality.
- If you encounter a compilation error, ensure that your compiler is installed and accessible.
- On Windows, use
MSVCfrom Visual Studio Build Tools. - On Linux/Mac, install
g++via your package manager. - If
ModuleNotFoundError: No module named 'algorithm'occurs, ensure you are runningtest.pyinside thesrcdirectory.
Feel free to fork and contribute by submitting pull requests!