From be9f6b6e8e39a711dcfa7806f894b8ec3ff49ca9 Mon Sep 17 00:00:00 2001 From: Jon Nordby Date: Sun, 27 Apr 2025 21:38:29 +0200 Subject: bindings: Example of using pybind11 with numpy --- bindings/.gitignore | 1 + bindings/README.md | 28 ++++++++++++++++++++++++++++ bindings/galearn_pdm.cpp | 29 +++++++++++++++++++++++++++++ bindings/setup.py | 22 ++++++++++++++++++++++ bindings/test_galearn_pdm.py | 16 ++++++++++++++++ 5 files changed, 96 insertions(+) create mode 100644 bindings/.gitignore create mode 100644 bindings/README.md create mode 100644 bindings/galearn_pdm.cpp create mode 100644 bindings/setup.py create mode 100644 bindings/test_galearn_pdm.py (limited to 'bindings') diff --git a/bindings/.gitignore b/bindings/.gitignore new file mode 100644 index 0000000..140f8cf --- /dev/null +++ b/bindings/.gitignore @@ -0,0 +1 @@ +*.so diff --git a/bindings/README.md b/bindings/README.md new file mode 100644 index 0000000..dee8dfc --- /dev/null +++ b/bindings/README.md @@ -0,0 +1,28 @@ + +# Python module + +## Prerequisites + +The following packages are needed. +Install with pip or via OS package manager. + + pybind11 + numpy + setuptools + + +## Building + +To build the module + + python setup.py build_ext --inplace + +This will produce a shared library (`.so` on Linux) in PWD, that Python can load. + +## Test + +To use the module, see the .py file + + python test_galearn_pdm.py + + diff --git a/bindings/galearn_pdm.cpp b/bindings/galearn_pdm.cpp new file mode 100644 index 0000000..9274a01 --- /dev/null +++ b/bindings/galearn_pdm.cpp @@ -0,0 +1,29 @@ +#include +#include + +namespace py = pybind11; + +void process(py::array_t arr1, py::array_t arr2) { + // Check shapes or sizes if needed + auto buf1 = arr1.request(); + auto buf2 = arr2.request(); + + if (buf1.ndim != 1 || buf2.ndim != 1) { + throw std::runtime_error("Only 1D arrays supported"); + } + + if (buf1.size < buf2.size) { + throw std::runtime_error("Input 1 must be same or larger than input 2"); + } + + // Example: access data + uint8_t* in = static_cast(buf1.ptr); + int16_t* out = static_cast(buf2.ptr); + for (int i=0; i