tree: 110caf627c80cd63555caf73adc95cd17de21a16 [search]
  1. 3rdparty/
  2. private/
  3. settings/
  4. test/
  5. toolchains/
  6. tools/
  7. .bazelignore
  8. .bazelrc
  9. .gitignore
  10. .isort.cfg
  11. .mypy.ini
  12. .pylintrc.toml
  13. BUILD.bazel
  14. defs.bzl
  15. MODULE.bazel
  16. README.md
  17. WORKSPACE.bazel
extensions/pyo3/README.md

rules_rust_pyo3

Bazel rules for PyO3.

Documentation

More information can be found in the rules_rust documentation.

Embedding CPython on Linux

A Rust executable can embed a standard shared CPython from the selected rules_python toolchain. Configure a non-abi3 PyO3 dependency with the target Python version, then link libpython on the executable.

For PyO3 0.29.3, add the following annotation to the crate universe hub that contains PyO3. The annotation keeps the same crate graph usable by both the executable and extension modules, which resolve Python symbols from the interpreter that imports them.

# MODULE.bazel
register_toolchains("@rules_rust_pyo3//toolchains:toolchain")

crate.annotation(
    crate = "pyo3-ffi",
    version = "0.29.3",
    repositories = ["my_crates"],
    build_script_env = {
        "PYO3_BUILD_EXTENSION_MODULE": "1",
        "PYO3_CROSS_PYTHON_VERSION": "$(PYO3_CROSS_PYTHON_VERSION)",
        "PYO3_NO_PYTHON": "1",
    },
    build_script_toolchains = ["@rules_rust_pyo3//:current_pyo3_toolchain"],
)

Use the annotated PyO3 crate from both rust_shared_library and the embedding executable. Add the C library dependency to the embedding executable's link_deps.

rust_binary(
    name = "embed_python",
    srcs = ["main.rs"],
    edition = "2021",
    deps = ["@my_crates//pyo3"],
    link_deps = ["@rules_python//python/cc:current_py_cc_libs"],
)

To make the toolchain‘s standard library available at runtime, include @rules_python//python:current_py_toolchain in its runfiles and configure Python’s module search path before initializing the interpreter. The embedding test sets PYTHONHOME to the runtime's installation directory.