pybind_library_test: fix PYTHONHOME setup

build_defs.bzl:
* Added a new pybind_py_env_test rule. This rule resolves the Python toolchain at analysis time, extracts the runtime
  path, and generates a shell wrapper script.
* The wrapper script dynamically identifies the absolute path to the Python runtime within the Bazel runfiles and sets
  the PYTHONHOME environment variable before executing the actual C++ test binary.
* Updated the pybind_library_test macro to build the C++ code as a private cc_binary and then wrap it with
  pybind_py_env_test.
1 file changed
tree: 98c347a0e1d805fe1a412a3df92c342292549832
  1. .github/
  2. examples/
  3. .bazelrc
  4. .gitignore
  5. AUTHORS
  6. BUILD.bazel
  7. build_defs.bzl
  8. CONTRIBUTING.md
  9. internal_configure.bzl
  10. LICENSE
  11. MODULE.bazel
  12. pybind11-BUILD.bazel
  13. README.md
  14. WORKSPACE.bazel
  15. WORKSPACE.bzlmod
README.md

Bazel extensions for pybind11

Github-CI: | OS \ Build system | Bazel | |:------- | :---: | | Linux (amd64) | Build Status | | MacOS (amd64) | Build Status | | MacOS (arm64) | Build Status | | Windows (amd64) | Build Status |

Provided rules:

  • pybind_extension: Builds a python extension, automatically adding the required build flags and pybind11 dependencies. It defines a target which can be included as a data dependency of a py_* target.
  • pybind_library: Builds a C++ library, automatically adding the required build flags and pybind11 dependencies. This library can then be used as a dependency of a pybind_extension. The arguments match a cc_library.
  • pybind_library_test: Builds a C++ test for a pybind_library. The arguments match a cc_test.

To test a pybind_extension, the most common approach is to write the test in Python and use the standard py_test build rule.

To embed Python, add @rules_python//python/cc:current_py_cc_libs as a dependency to your cc_binary.

Installation

In your WORKSPACE file:

http_archive(
  name = "pybind11_bazel",
  strip_prefix = "pybind11_bazel-<version>",
  urls = ["https://github.com/pybind/pybind11_bazel/archive/v<version>.zip"],
)
# We still require the pybind library.
http_archive(
  name = "pybind11",
  build_file = "@pybind11_bazel//:pybind11-BUILD.bazel",
  strip_prefix = "pybind11-<version>",
  urls = ["https://github.com/pybind/pybind11/archive/v<version>.zip"],
)

Then, in your BUILD file:

load("@pybind11_bazel//:build_defs.bzl", "pybind_extension")

Bzlmod

In your MODULE.bazel file:

bazel_dep(name = "pybind11_bazel", version = "<version>")

Usage in your BUILD file is as described previously.