From 7c4f6015537809a92785e3809ee71682cdd6b5aa Mon Sep 17 00:00:00 2001 From: Markus Hofbauer Date: Wed, 20 Nov 2024 15:14:09 +0100 Subject: [PATCH] example: Add example for pybind11 (#375) Add an example for pybind11 with rules_py which is a modified version of https://github.com/pybind/pybind11_bazel/tree/master/examples/basic. --- ### Changes are visible to end-users: no ### Test plan - New test cases added --- MODULE.bazel | 2 ++ examples/pybind11/BUILD.bazel | 19 +++++++++++++++++++ examples/pybind11/basic.cpp | 10 ++++++++++ examples/pybind11/basic_test.py | 14 ++++++++++++++ 4 files changed, 45 insertions(+) create mode 100644 examples/pybind11/BUILD.bazel create mode 100644 examples/pybind11/basic.cpp create mode 100644 examples/pybind11/basic_test.py diff --git a/MODULE.bazel b/MODULE.bazel index e2375770..18da9029 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -85,3 +85,5 @@ crate.from_cargo( ) use_repo(crate, "crate_index") + +bazel_dep(name = "pybind11_bazel", version = "2.12.0", dev_dependency = True) diff --git a/examples/pybind11/BUILD.bazel b/examples/pybind11/BUILD.bazel new file mode 100644 index 00000000..74a49fd6 --- /dev/null +++ b/examples/pybind11/BUILD.bazel @@ -0,0 +1,19 @@ +load("@aspect_rules_py//py:defs.bzl", "py_library", "py_test") +load("@pybind11_bazel//:build_defs.bzl", "pybind_extension") + +pybind_extension( + name = "basic", + srcs = ["basic.cpp"], +) + +py_library( + name = "basic_lib", + data = [":basic"], + imports = ["."], +) + +py_test( + name = "basic_test", + srcs = ["basic_test.py"], + deps = [":basic_lib"], +) diff --git a/examples/pybind11/basic.cpp b/examples/pybind11/basic.cpp new file mode 100644 index 00000000..4996ac37 --- /dev/null +++ b/examples/pybind11/basic.cpp @@ -0,0 +1,10 @@ +#include + +int add(int i, int j) { + return i + j; +} + +PYBIND11_MODULE(basic, module) { + module.doc() = "A basic pybind11 extension"; + module.def("add", &add, "A function that adds two numbers"); +} diff --git a/examples/pybind11/basic_test.py b/examples/pybind11/basic_test.py new file mode 100644 index 00000000..0a1f15ad --- /dev/null +++ b/examples/pybind11/basic_test.py @@ -0,0 +1,14 @@ +import unittest + +import basic + + +class TestBasic(unittest.TestCase): + + def test_add(self): + self.assertEqual(basic.add(1, 2), 3) + self.assertEqual(basic.add(2, 2), 4) + + +if __name__ == "__main__": + unittest.main()