From e4e1ac4b2c7bf2e968a3b82c9c54576f0260669d Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:08:05 -0500 Subject: [PATCH 1/4] Add a C ABI library option to the rust template add_c_abi adds rust/capi, a crate that builds lib_capi with an extern "C" surface over the Rust crate. build.rs writes the header through cbindgen and the project checks it in; make lint-rs fails on drift. hatch-rs ships the library under /lib with the header under /include/, and the PyO3 extension links against it instead of compiling the crate in. The extension crate's capi and direct features follow hatch-rs's library-source, so wheels bundle the library, conda builds can use an external one, and Pyodide compiles the crate in. The package exposes get_prefix, get_include, get_library_dirs, and get_libraries, and adds its lib directory to the Windows DLL search path. Wheel repair keeps the bundled library. rust/rustfmt.toml sets max_width = 150 so generated code stays formatted for long module names. A rust-capi example and gen/test targets exercise the option in CI. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- .github/workflows/build.yaml | 7 +- Makefile | 17 ++- README.md | 2 +- copier.yaml | 6 + examples/rust-capi.yaml | 12 ++ python/rust/.gitignore.jinja | 5 +- python/rust/Cargo.toml.jinja | 9 +- python/rust/Makefile.jinja | 3 +- python/rust/README.md.jinja | 15 +++ python/rust/pyproject.toml.jinja | 58 ++++++++- python/rust/rust/Cargo.toml.jinja | 7 ++ python/rust/rust/python/example/mod.rs.jinja | 43 +++++++ python/rust/rust/python/lib.rs.jinja | 4 + ...{% if add_c_abi %}capi.rs{% endif %}.jinja | 48 ++++++++ .../Cargo.toml.jinja | 21 ++++ .../build.rs.jinja | 31 +++++ .../cbindgen.toml.jinja | 14 +++ .../src/lib.rs.jinja | 114 ++++++++++++++++++ .../{% if add_c_abi %}rustfmt.toml{% endif %} | 1 + python/rust/{{module}}/__init__.py | 1 - python/rust/{{module}}/__init__.py.jinja | 30 +++++ .../rust/{{module}}/tests/test_all.py.jinja | 28 +++++ 22 files changed, 460 insertions(+), 16 deletions(-) create mode 100644 examples/rust-capi.yaml create mode 100644 python/rust/rust/python/{% if add_c_abi %}capi.rs{% endif %}.jinja create mode 100644 python/rust/rust/{% if add_c_abi %}capi{% endif %}/Cargo.toml.jinja create mode 100644 python/rust/rust/{% if add_c_abi %}capi{% endif %}/build.rs.jinja create mode 100644 python/rust/rust/{% if add_c_abi %}capi{% endif %}/cbindgen.toml.jinja create mode 100644 python/rust/rust/{% if add_c_abi %}capi{% endif %}/src/lib.rs.jinja create mode 100644 python/rust/rust/{% if add_c_abi %}rustfmt.toml{% endif %} delete mode 100644 python/rust/{{module}}/__init__.py create mode 100644 python/rust/{{module}}/__init__.py.jinja diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 1d947db..22b09ea 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -30,6 +30,7 @@ jobs: - js - jupyter - rust + - rust-capi - rustjswasm - cppjswasm - uitk-svelte @@ -100,7 +101,7 @@ jobs: - name: Setup Rust uses: actions-ext/rust/setup@af6343171cd1a86c4183da96de7eb96e15599662 - if: matrix.template == 'rust' || matrix.template == 'rustjswasm' + if: matrix.template == 'rust' || matrix.template == 'rust-capi' || matrix.template == 'rustjswasm' - name: Install JavaScript dependencies run: pnpm install @@ -108,7 +109,7 @@ jobs: - name: Build Rust fixture run: cargo build - if: matrix.template == 'rust' || matrix.template == 'rustjswasm' + if: matrix.template == 'rust' || matrix.template == 'rust-capi' || matrix.template == 'rustjswasm' - name: Generate template run: make gen-${{ matrix.template }} @@ -133,4 +134,4 @@ jobs: run: python .github/scripts/check_sdist_artifacts.py ../python-template-${{ matrix.template }} env: HATCH_BUILD_NO_HOOKS: '1' - if: matrix.template == 'cpp' || matrix.template == 'cppjswasm' || matrix.template == 'rust' || matrix.template == 'rustjswasm' + if: matrix.template == 'cpp' || matrix.template == 'cppjswasm' || matrix.template == 'rust' || matrix.template == 'rust-capi' || matrix.template == 'rustjswasm' diff --git a/Makefile b/Makefile index 3517123..14c7b8b 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ update-action-pins: ## re-pin actions-ext references to each action repo's curr check-action-pins: ## check whether any actions-ext pin is out of date python3 .github/scripts/update_action_pins.py --check -.PHONY: gen-python gen-cpp gen-js gen-jupyter gen-rust gen-rustjswasm gen-cppjswasm gen-uitk-svelte gen-uitk-webawesome gen-site-react gen-site-sveltekit gen-site-webawesome +.PHONY: gen-python gen-cpp gen-js gen-jupyter gen-rust gen-rust-capi gen-rustjswasm gen-cppjswasm gen-uitk-svelte gen-uitk-webawesome gen-site-react gen-site-sveltekit gen-site-webawesome gen-python: ## regenerate the python template from scratch mkdir -p ../python-template && cd ../python-template && rm -rf ./* && rm -rf .copier-answers.yaml .gitignore .github .gitattributes copier copy -w . ../python-template --data-file examples/python.yaml @@ -67,6 +67,11 @@ gen-rust: ## regenerate the rust template from scratch copier copy -w . ../python-template-rust --data-file examples/rust.yaml cd ../python-template-rust && $(SED) 's#_src_path: .#_src_path: https://github.com/python-project-templates/base.git#g' ./.copier-answers.yaml +gen-rust-capi: ## regenerate the rust template with a C ABI library from scratch + mkdir -p ../python-template-rust-capi && cd ../python-template-rust-capi && rm -rf ./* && rm -rf .copier-answers.yaml .gitignore .github .gitattributes + copier copy -w . ../python-template-rust-capi --data-file examples/rust-capi.yaml + cd ../python-template-rust-capi && $(SED) 's#_src_path: .#_src_path: https://github.com/python-project-templates/base.git#g' ./.copier-answers.yaml + gen-rustjswasm: ## regenerate the rustjswasm template from scratch mkdir -p ../python-template-rustjswasm && cd ../python-template-rustjswasm && rm -rf ./* && rm -rf .copier-answers.yaml .gitignore .github .gitattributes copier copy -w . ../python-template-rustjswasm --data-file examples/rustjswasm.yaml @@ -97,7 +102,7 @@ gen-site-webawesome: ## regenerate the Web Awesome site template from scratch mkdir -p ../javascript-template-site-webawesome && cd ../javascript-template-site-webawesome && rm -rf ./* && rm -rf .copier-answers.yaml .github .gitignore .prettierignore .prettierrc .oxfmtrc.json .oxlintrc.json copier copy -w . ../javascript-template-site-webawesome --data-file examples/site-webawesome.yaml -.PHONY: test-python test-cpp test-js test-jupyter test-rust test-rustjswasm test-cppjswasm test-uitk-svelte test-uitk-webawesome test-site-react test-site-sveltekit test-site-webawesome +.PHONY: test-python test-cpp test-js test-jupyter test-rust test-rust-capi test-rustjswasm test-cppjswasm test-uitk-svelte test-uitk-webawesome test-site-react test-site-sveltekit test-site-webawesome test-python: cd ../python-template && git config --global user.name "github-actions" && git config --global user.email "41898282+github-actions[bot]@users.noreply.github.c@example.com" && git init && git add . && git commit -m "initial commit" cd ../python-template && make develop @@ -136,6 +141,14 @@ test-rust: cd ../python-template-rust && make checks cd ../python-template-rust && make test +test-rust-capi: + cd ../python-template-rust-capi && git config --global user.name "github-actions" && git config --global user.email "41898282+github-actions[bot]@users.noreply.github.c@example.com" && git init && git add . && git commit -m "initial commit" + cd ../python-template-rust-capi && make develop + cd ../python-template-rust-capi && git add Cargo.lock rust/Cargo.lock rust/capi/include && git commit -m "lockfile and header" + cd ../python-template-rust-capi && make lint + cd ../python-template-rust-capi && make checks + cd ../python-template-rust-capi && make test + test-rustjswasm: cd ../python-template-rustjswasm && git config --global user.name "github-actions" && git config --global user.email "41898282+github-actions[bot]@users.noreply.github.c@example.com" && git init && git add . && git commit -m "initial commit" cd ../python-template-rustjswasm && make develop diff --git a/README.md b/README.md index f2e1688..ccabe87 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ One selector chooses a template: - `Python / Cython` generates a Python package with compiled `.py` and `.pyx` modules from `python/cython/`. - `Python / C++` generates a Python/C++ package with pybind11 bindings or standalone C++ code from `python/cpp/`. - `Python / JavaScript` generates a Python package with a self-contained JavaScript frontend from `python/js/`. -- `Python / Rust` generates a Python package with Rust bindings via PyO3 from `python/rust/`. +- `Python / Rust` generates a Python package with Rust bindings via PyO3 from `python/rust/`. With `add_c_abi`, it also builds a C ABI library that the extension links against and wheels ship with its header. - `Python / Jupyter Widget` generates a Python package with a Jupyter extension from `python/jupyter/`. - `Python / Rust + JavaScript + WebAssembly` generates a Rust package with Python and WebAssembly bindings from `python/rustjswasm/`. - `Python / C++ + JavaScript + WebAssembly` generates a C++ package with Python and WebAssembly bindings from `python/cppjswasm/`. diff --git a/copier.yaml b/copier.yaml index 6e204fe..6486eaa 100644 --- a/copier.yaml +++ b/copier.yaml @@ -81,6 +81,12 @@ add_pyodide: help: Build and test Pyodide wheels when: "{{ add_extension in ['cpp', 'rust', 'cppjswasm', 'rustjswasm'] }}" +add_c_abi: + type: bool + default: false + help: Build a C ABI library that the Python extension links against + when: "{{ add_extension == 'rust' }}" + python_version_primary: type: str default: 3.11 diff --git a/examples/rust-capi.yaml b/examples/rust-capi.yaml new file mode 100644 index 0000000..358f46d --- /dev/null +++ b/examples/rust-capi.yaml @@ -0,0 +1,12 @@ +--- +add_docs: true +add_pyodide: false +add_wiki: true +add_c_abi: true +add_extension: rust +email: 3105306+timkpaine@users.noreply.github.com +github: python-project-templates +project_description: A Rust-Python project template with a C ABI library +project_name: python template rust capi +python_version_primary: '3.11' +team: Python Project Template Authors diff --git a/python/rust/.gitignore.jinja b/python/rust/.gitignore.jinja index 7873e43..949b916 100644 --- a/python/rust/.gitignore.jinja +++ b/python/rust/.gitignore.jinja @@ -20,7 +20,10 @@ vcpkg_installed/ # Rust target target-capi - +{% if add_c_abi %} +# Copied from rust/capi/include by hatch-rs +{{ module }}/include/ +{% endif %} # Distribution / packaging .Python build/ diff --git a/python/rust/Cargo.toml.jinja b/python/rust/Cargo.toml.jinja index 35497a9..4c17f2d 100644 --- a/python/rust/Cargo.toml.jinja +++ b/python/rust/Cargo.toml.jinja @@ -10,9 +10,14 @@ path = "rust/python/lib.rs" crate-type = ["cdylib"] [dependencies] -{{ module }} = { path = "./rust", version = "*" } +{{ module }} = { path = "./rust", version = "*"{% if add_c_abi %}, optional = true{% endif %} } pyo3 = { version = "0.29.2", features = ["abi3", "extension-module", "multiple-pymethods"] } - +{% if add_c_abi %} +[features] +default = ["direct"] +capi = [] +direct = ["dep:{{ module }}"] +{% endif %} [profile.release] panic = 'abort' lto = true diff --git a/python/rust/Makefile.jinja b/python/rust/Makefile.jinja index 5fd8a54..0028dd0 100644 --- a/python/rust/Makefile.jinja +++ b/python/rust/Makefile.jinja @@ -42,7 +42,8 @@ lint-py: ## run python linter with ruff lint-rs: ## run rust linter make -C rust lint - +{% if add_c_abi %} git diff --exit-code -- rust/capi/include/{{ module }}.h +{% endif %} lint-docs: ## lint docs with mdformat and codespell python -m mdformat --check README.md $(wildcard docs/src) {% if add_wiki %}docs/wiki/{% endif %} python -m codespell_lib README.md $(wildcard docs/src) {% if add_wiki %}docs/wiki/{% endif %} diff --git a/python/rust/README.md.jinja b/python/rust/README.md.jinja index 7e11b1c..8d55e40 100644 --- a/python/rust/README.md.jinja +++ b/python/rust/README.md.jinja @@ -8,6 +8,21 @@ [![PyPI](https://img.shields.io/pypi/v/{{ project_name_formatted }}.svg)](https://pypi.python.org/pypi/{{ project_name_formatted }}) ## Overview +{% if add_c_abi %} +## C ABI + +`rust/capi` builds `lib{{ module }}_capi`, a C ABI over the Rust crate with the +header `rust/capi/include/{{ module }}.h`. Wheels ship the library under +`{{ module }}/lib` and the header under `{{ module }}/include/{{ module }}`, and the +Python extension links against it rather than compiling the crate in. Other +projects build against the installed wheel with `{{ module }}.get_include()`, +`get_library_dirs()`, `get_libraries()`, and `get_prefix()`. + +`HATCH_RS_LIBRARY_SOURCE` chooses where the library comes from at build time: +`bundled` (the default, for wheels), `external` (a prebuilt library found +through `HATCH_RS_LIBRARY_ROOT`, pkg-config, or the conda prefix), or `direct` +(compile the crate in). +{% endif %} > [!NOTE] > This library was generated using [copier](https://copier.readthedocs.io/en/stable/) from the [Base Python Project Template repository](https://github.com/python-project-templates/base). diff --git a/python/rust/pyproject.toml.jinja b/python/rust/pyproject.toml.jinja index 2b66f0f..7961d0d 100644 --- a/python/rust/pyproject.toml.jinja +++ b/python/rust/pyproject.toml.jinja @@ -1,7 +1,7 @@ [build-system] requires = [ "hatchling", - "hatch-rs>={% if add_pyodide %}0.3.0{% else %}0.1.4{% endif %}", + "hatch-rs>={% if add_c_abi %}0.5.0{% elif add_pyodide %}0.3.0{% else %}0.1.4{% endif %}", ] build-backend = "hatchling.build" @@ -46,7 +46,7 @@ develop = [ "check-dist", "cibuildwheel", "codespell", - "hatch-rs{% if add_pyodide %}>=0.3.0{% endif %}", + "hatch-rs{% if add_c_abi %}>=0.5.0{% elif add_pyodide %}>=0.3.0{% endif %}", "hatchling", "mdformat", "mdformat-myst", @@ -96,7 +96,12 @@ replace = 'version = "{new_version}"' filename = "rust/Cargo.toml" search = 'version = "{current_version}"' replace = 'version = "{new_version}"' - +{% if add_c_abi %} +[[tool.bumpversion.files]] +filename = "rust/capi/Cargo.toml" +search = 'version = "{current_version}"' +replace = 'version = "{new_version}"' +{% endif %} [tool.cibuildwheel] build = "cp{{ python_version_primary.replace('.', '') }}-*" test-command = "pytest -vvv {project}/{{ module }}/tests" @@ -112,11 +117,16 @@ rustup show before-build = "cargo clean --manifest-path {package}/Cargo.toml && rm -f {package}/{{ module }}/*.so" environment = {PATH="$HOME/.cargo/bin:$PATH", CARGO_TERM_COLOR="always"} skip = "*i686* *musllinux*" - +{% if add_c_abi -%} +# Keep the bundled C ABI library where the extension's rpath expects it. +repair-wheel-command = "auditwheel repair --exclude 'lib{{ module }}_capi.so*' -w {dest_dir} {wheel}" +{% endif %} [tool.cibuildwheel.macos] environment = {PATH="$HOME/.cargo/bin:$PATH", CARGO_TERM_COLOR="always", MACOS_DEPLOYMENT_TARGET=11.0} archs = "arm64" - +{% if add_c_abi -%} +repair-wheel-command = "delocate-wheel --require-archs {delocate_archs} --exclude {{ module }}_capi -w {dest_dir} -v {wheel}" +{% endif %} [tool.cibuildwheel.windows] environment = {PATH="$UserProfile\\.cargo\bin;$PATH", CARGO_TERM_COLOR="always"} skip = "*win32 *arm64" @@ -127,6 +137,10 @@ test-command = "python -m pytest -vvv --pyargs {{ module }}.tests" test-extras = [] test-requires = ["pytest"] xbuild-tools = ["cargo", "rustc", "rustup"] +{% if add_c_abi -%} +# Emscripten has no shared libraries to split; compile the library in. +environment = {HATCH_RS_LIBRARY_SOURCE="direct"} +{% endif -%} {% endif %} [tool.coverage.run] branch = true @@ -151,7 +165,37 @@ verbose = true abi3 = true module = "{{ module }}" path = "." +{% if add_c_abi -%} +target-dir = "project" + +# lib{{ module }}_capi: the C ABI library, shipped under {{ module }}/lib with its header. +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "{{ module }}_capi" +manifest = "rust/capi/Cargo.toml" +destination = "{{ module }}/lib/{shared_library}" +expected-headers = ["rust/capi/include/{{ module }}.h"] +header-symbol-prefix = "{{ module }}_" +expected-abi-strings = ["{{ module | upper }}_ABI_VERSION"] +include-import-lib = true + +[[tool.hatch.build.hooks.hatch-rs.artifacts.outputs]] +source = "rust/capi/include/{{ module }}.h" +destination = "{{ module }}/include/{{ module }}/{{ module }}.h" +install-scheme = "package" +# The PyO3 extension, linked against the library by default (library-source = bundled). +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "{{ module }}" +manifest = "Cargo.toml" +destination = "{{ module }}/{python_extension_name}" +links = ["{{ module }}_capi"] + +[tool.hatch.build.hooks.hatch-rs.artifacts.library-source-features] +bundled = ["capi"] +external = ["capi"] +static = ["direct"] +direct = ["direct"] +{% endif %} [tool.hatch.build.targets.sdist] packages = [ "{{ module }}", @@ -173,6 +217,10 @@ artifacts = [ "{{ module }}/*.dll", "{{ module }}/*.dylib", "{{ module }}/*.so", + {% if add_c_abi -%} + "{{ module }}/include/**/*.h", + "{{ module }}/lib/*", + {% endif -%} ] packages = [ "{{ module }}", diff --git a/python/rust/rust/Cargo.toml.jinja b/python/rust/rust/Cargo.toml.jinja index 8eee201..43c3ba3 100644 --- a/python/rust/rust/Cargo.toml.jinja +++ b/python/rust/rust/Cargo.toml.jinja @@ -14,4 +14,11 @@ path = "src/lib.rs" crate-type = ["rlib"] [dependencies] +{%- if add_c_abi %} +[workspace] +members = [ + ".", + "capi", +] +{%- endif %} diff --git a/python/rust/rust/python/example/mod.rs.jinja b/python/rust/rust/python/example/mod.rs.jinja index 7c1e7f9..01846d6 100644 --- a/python/rust/rust/python/example/mod.rs.jinja +++ b/python/rust/rust/python/example/mod.rs.jinja @@ -1,5 +1,47 @@ use pyo3::prelude::*; +{% if add_c_abi -%} +// The resolution switch picks the route at build time: `capi` calls through +// lib{{ module }}_capi (bundled or external), `direct` compiles the Rust crate in. +#[cfg(feature = "capi")] +use crate::capi::Example as BaseExample; +#[cfg(feature = "direct")] +use {{ module }}::Example as BaseExample; + +#[cfg(feature = "capi")] +fn stuff(example: &BaseExample) -> String { + example.stuff() +} + +#[cfg(feature = "direct")] +fn stuff(example: &BaseExample) -> String { + example.stuff.clone() +} + + +#[pyclass] +pub struct Example { + pub example: BaseExample, +} + +#[pymethods] +impl Example { + #[new] + fn py_new(value: String) -> PyResult { + Ok(Example { + example: BaseExample::new(value), + }) + } + + fn __str__(&self) -> PyResult { + Ok(stuff(&self.example)) + } + + fn __repr__(&self) -> PyResult { + Ok(format!("Example<{}>", stuff(&self.example))) + } +} +{%- else -%} use {{ module }}::Example as BaseExample; @@ -30,3 +72,4 @@ impl Example { Ok(format!("Example<{}>", self.example.stuff)) } } +{%- endif %} diff --git a/python/rust/rust/python/lib.rs.jinja b/python/rust/rust/python/lib.rs.jinja index 168dfeb..9f33f2d 100644 --- a/python/rust/rust/python/lib.rs.jinja +++ b/python/rust/rust/python/lib.rs.jinja @@ -1,5 +1,9 @@ use pyo3::prelude::*; +{% if add_c_abi -%} +#[cfg(feature = "capi")] +mod capi; +{% endif -%} mod example; pub use example::Example; diff --git a/python/rust/rust/python/{% if add_c_abi %}capi.rs{% endif %}.jinja b/python/rust/rust/python/{% if add_c_abi %}capi.rs{% endif %}.jinja new file mode 100644 index 0000000..bed40ac --- /dev/null +++ b/python/rust/rust/python/{% if add_c_abi %}capi.rs{% endif %}.jinja @@ -0,0 +1,48 @@ +//! Bindings to `lib{{ module }}_capi`. hatch-rs links the library and sets the +//! rpath, so no `#[link]` attribute is needed here. + +use std::ffi::{c_char, CStr}; + +#[repr(C)] +pub struct {{ module }}_example { + _private: [u8; 0], +} + +extern "C" { + pub fn {{ module }}_abi_version() -> u32; + pub fn {{ module }}_example_new(value: *const c_char, len: usize) -> *mut {{ module }}_example; + pub fn {{ module }}_example_stuff(example: *const {{ module }}_example) -> *mut c_char; + pub fn {{ module }}_example_free(example: *mut {{ module }}_example); + pub fn {{ module }}_string_free(string: *mut c_char); +} + +/// An example owned by `lib{{ module }}_capi`. +pub struct Example { + handle: *mut {{ module }}_example, +} + +unsafe impl Send for Example {} +unsafe impl Sync for Example {} + +impl Example { + pub fn new(value: String) -> Self { + let handle = unsafe { {{ module }}_example_new(value.as_ptr() as *const c_char, value.len()) }; + assert!(!handle.is_null(), "lib{{ module }}_capi rejected the value"); + Self { handle } + } + + pub fn stuff(&self) -> String { + unsafe { + let stuff = {{ module }}_example_stuff(self.handle); + let value = CStr::from_ptr(stuff).to_string_lossy().into_owned(); + {{ module }}_string_free(stuff); + value + } + } +} + +impl Drop for Example { + fn drop(&mut self) { + unsafe { {{ module }}_example_free(self.handle) } + } +} diff --git a/python/rust/rust/{% if add_c_abi %}capi{% endif %}/Cargo.toml.jinja b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/Cargo.toml.jinja new file mode 100644 index 0000000..d5e90cf --- /dev/null +++ b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/Cargo.toml.jinja @@ -0,0 +1,21 @@ +[package] +name = "{{ module }}_capi" +version = "0.1.0" +authors = ["{{ team }} <{{ email }}>"] +edition = "2021" +license = "Apache-2.0" +readme = "../../README.md" +repository = "https://github.com/{{ github }}/{{ project_name }}" +description = "C ABI for {{ project_name }}" +build = "build.rs" + +[lib] +name = "{{ module }}_capi" +path = "src/lib.rs" +crate-type = ["cdylib", "rlib"] + +[dependencies] +{{ module }} = { path = "..", version = "0.1.0" } + +[build-dependencies] +cbindgen = { version = "0.29", default-features = false } diff --git a/python/rust/rust/{% if add_c_abi %}capi{% endif %}/build.rs.jinja b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/build.rs.jinja new file mode 100644 index 0000000..a7a2207 --- /dev/null +++ b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/build.rs.jinja @@ -0,0 +1,31 @@ +use std::env; +use std::path::PathBuf; + +fn main() { + let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let header = crate_dir.join("include").join("{{ module }}.h"); + println!("cargo:rerun-if-changed=src"); + println!("cargo:rerun-if-changed=cbindgen.toml"); + + // cbindgen reads `cargo metadata`, which is unavailable inside a packaged + // crate (`cargo publish`, `cargo install`). Those builds use the checked-in + // header, which `make lint-rs` keeps in sync with the source. + let generated = cbindgen::Config::from_file(crate_dir.join("cbindgen.toml")) + .map_err(|error| error.to_string()) + .and_then(|config| { + cbindgen::Builder::new() + .with_crate(&crate_dir) + .with_config(config) + .generate() + .map_err(|error| error.to_string()) + }); + match generated { + Ok(bindings) => { + bindings.write_to_file(&header); + } + Err(error) if header.is_file() => { + println!("cargo:warning=using the checked-in {{ module }}.h; cbindgen could not run: {error}"); + } + Err(error) => panic!("cbindgen failed to generate {{ module }}.h and no checked-in copy exists: {error}"), + } +} diff --git a/python/rust/rust/{% if add_c_abi %}capi{% endif %}/cbindgen.toml.jinja b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/cbindgen.toml.jinja new file mode 100644 index 0000000..2597afa --- /dev/null +++ b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/cbindgen.toml.jinja @@ -0,0 +1,14 @@ +language = "C" +cpp_compat = true +include_guard = "{{ module | upper }}_H" +include_version = false +autogen_warning = "/* Generated by cbindgen from rust/capi/src; edit the Rust source instead. */" +documentation = true +style = "both" +usize_is_size_t = true + +[enum] +prefix_with_name = false + +[parse] +parse_deps = false diff --git a/python/rust/rust/{% if add_c_abi %}capi{% endif %}/src/lib.rs.jinja b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/src/lib.rs.jinja new file mode 100644 index 0000000..9a994f6 --- /dev/null +++ b/python/rust/rust/{% if add_c_abi %}capi{% endif %}/src/lib.rs.jinja @@ -0,0 +1,114 @@ +//! C ABI for {{ project_name }}: `lib{{ module }}_capi`. +//! +//! Handles are opaque and freed with their matching `_free` function. Strings +//! are passed in as UTF-8 pointer plus length and returned NUL-terminated. +//! Every entry point catches panics; a failure is reported as null. + +#![allow(clippy::missing_safety_doc)] +#![allow(non_camel_case_types)] + +use std::ffi::{c_char, CString}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::ptr; +use std::slice; + +use {{ module }}::Example; + +/// The ABI version of this header and library. A caller built against a +/// different version must not use the library. +pub const {{ module | upper }}_ABI_VERSION: u32 = 1; + +/// An example value. Create with `{{ module }}_example_new` and free with +/// `{{ module }}_example_free`. +pub struct {{ module }}_example { + inner: Example, +} + +/// The ABI version this library was built with. +#[no_mangle] +pub extern "C" fn {{ module }}_abi_version() -> u32 { + {{ module | upper }}_ABI_VERSION +} + +/// Creates an example from a UTF-8 `value` of `len` bytes. Returns null when +/// the value is not UTF-8. +#[no_mangle] +pub unsafe extern "C" fn {{ module }}_example_new(value: *const c_char, len: usize) -> *mut {{ module }}_example { + catch_unwind(AssertUnwindSafe(|| { + if value.is_null() && len != 0 { + return ptr::null_mut(); + } + let bytes = if len == 0 { + &[][..] + } else { + slice::from_raw_parts(value as *const u8, len) + }; + match std::str::from_utf8(bytes) { + Ok(value) => Box::into_raw(Box::new({{ module }}_example { + inner: Example::new(value.to_string()), + })), + Err(_) => ptr::null_mut(), + } + })) + .unwrap_or(ptr::null_mut()) +} + +/// The example's value as a NUL-terminated string. Free with +/// `{{ module }}_string_free`. Returns null for a null example. +#[no_mangle] +pub unsafe extern "C" fn {{ module }}_example_stuff(example: *const {{ module }}_example) -> *mut c_char { + match example.as_ref() { + Some(example) => CString::new(example.inner.stuff.clone()) + .map(CString::into_raw) + .unwrap_or(ptr::null_mut()), + None => ptr::null_mut(), + } +} + +/// Frees an example. Null is ignored. +#[no_mangle] +pub unsafe extern "C" fn {{ module }}_example_free(example: *mut {{ module }}_example) { + if !example.is_null() { + drop(Box::from_raw(example)); + } +} + +/// Frees a string returned by this library. Null is ignored. +#[no_mangle] +pub unsafe extern "C" fn {{ module }}_string_free(string: *mut c_char) { + if !string.is_null() { + drop(CString::from_raw(string)); + } +} + +#[cfg(test)] +mod tests { + use std::ffi::CStr; + + use super::*; + + #[test] + fn example_round_trip() { + assert_eq!({{ module }}_abi_version(), {{ module | upper }}_ABI_VERSION); + let value = "test"; + let example = unsafe { {{ module }}_example_new(value.as_ptr() as *const c_char, value.len()) }; + assert!(!example.is_null()); + let stuff = unsafe { {{ module }}_example_stuff(example) }; + assert_eq!(unsafe { CStr::from_ptr(stuff) }.to_str().unwrap(), "test"); + unsafe { + {{ module }}_string_free(stuff); + {{ module }}_example_free(example); + } + } + + #[test] + fn invalid_input_is_null() { + assert!(unsafe { {{ module }}_example_new(ptr::null(), 1) }.is_null()); + assert!(unsafe { {{ module }}_example_new(b"\xff".as_ptr() as *const c_char, 1) }.is_null()); + assert!(unsafe { {{ module }}_example_stuff(ptr::null()) }.is_null()); + unsafe { + {{ module }}_example_free(ptr::null_mut()); + {{ module }}_string_free(ptr::null_mut()); + } + } +} diff --git a/python/rust/rust/{% if add_c_abi %}rustfmt.toml{% endif %} b/python/rust/rust/{% if add_c_abi %}rustfmt.toml{% endif %} new file mode 100644 index 0000000..bc30bf4 --- /dev/null +++ b/python/rust/rust/{% if add_c_abi %}rustfmt.toml{% endif %} @@ -0,0 +1 @@ +max_width = 150 diff --git a/python/rust/{{module}}/__init__.py b/python/rust/{{module}}/__init__.py deleted file mode 100644 index 3dc1f76..0000000 --- a/python/rust/{{module}}/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.1.0" diff --git a/python/rust/{{module}}/__init__.py.jinja b/python/rust/{{module}}/__init__.py.jinja new file mode 100644 index 0000000..48a65c4 --- /dev/null +++ b/python/rust/{{module}}/__init__.py.jinja @@ -0,0 +1,30 @@ +__version__ = "0.1.0" +{%- if add_c_abi %} + +import os as _os +from pathlib import Path as _Path + +_PREFIX = _Path(__file__).resolve().parent +if _os.name == "nt" and (_PREFIX / "lib").is_dir(): + _DLL_DIRECTORY = _os.add_dll_directory(str(_PREFIX / "lib")) + + +def get_prefix() -> str: + """The installed package directory, usable as a CMake prefix for lib{{ module }}_capi.""" + return str(_PREFIX) + + +def get_include() -> str: + """The directory holding ``{{ module }}/{{ module }}.h``.""" + return str(_PREFIX / "include") + + +def get_library_dirs() -> list[str]: + """Directories holding the bundled lib{{ module }}_capi shared library.""" + return [str(_PREFIX / "lib")] + + +def get_libraries() -> list[str]: + """Link names for lib{{ module }}_capi, for ``-l`` or ``target_link_libraries``.""" + return ["{{ module }}_capi"] +{%- endif %} diff --git a/python/rust/{{module}}/tests/test_all.py.jinja b/python/rust/{{module}}/tests/test_all.py.jinja index 1c802c0..2ea4b8b 100644 --- a/python/rust/{{module}}/tests/test_all.py.jinja +++ b/python/rust/{{module}}/tests/test_all.py.jinja @@ -1,5 +1,33 @@ +{% if add_c_abi -%} +from ctypes import CDLL, c_uint32 +from pathlib import Path +from sys import platform + +import pytest + +from {{ module }} import get_include, get_libraries, get_library_dirs +from {{ module }}.{{ module }} import Example + + +def test_example_round_trips_through_the_library(): + assert str(Example("test")) == "test" + assert repr(Example("test")) == "Example" + + +def test_c_library_and_header_are_installed(): + if platform == "emscripten": + pytest.skip("Pyodide wheels compile the library in") + header = Path(get_include()) / "{{ module }}" / "{{ module }}.h" + assert "#define {{ module | upper }}_ABI_VERSION 1" in header.read_text() + (name,) = get_libraries() + filename = f"{name}.dll" if platform == "win32" else f"lib{name}.dylib" if platform == "darwin" else f"lib{name}.so" + library = CDLL(str(Path(get_library_dirs()[0]) / filename)) + library.{{ module }}_abi_version.restype = c_uint32 + assert library.{{ module }}_abi_version() == 1 +{%- else -%} from {{ module }}{% if add_pyodide %}.{{ module }} import Example{% else %} import *{% endif %} def test_all(): assert {% if add_pyodide %}str(Example("test")) == "test"{% else %}True{% endif %} +{%- endif %} From 6502091edc0a81c4ba9cdda5b37edcdceea65924 Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:28:31 -0500 Subject: [PATCH 2/4] Fix rust example answers and README spacing for add_c_abi copier needs every question answered to run without a prompt, and the rendered README had two blank lines after the C ABI section. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- examples/rust.yaml | 1 + python/rust/README.md.jinja | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/rust.yaml b/examples/rust.yaml index 6fad72c..7954264 100644 --- a/examples/rust.yaml +++ b/examples/rust.yaml @@ -2,6 +2,7 @@ add_docs: true add_pyodide: false add_wiki: true +add_c_abi: false add_extension: rust email: 3105306+timkpaine@users.noreply.github.com github: python-project-templates diff --git a/python/rust/README.md.jinja b/python/rust/README.md.jinja index 8d55e40..ec8d20e 100644 --- a/python/rust/README.md.jinja +++ b/python/rust/README.md.jinja @@ -8,7 +8,8 @@ [![PyPI](https://img.shields.io/pypi/v/{{ project_name_formatted }}.svg)](https://pypi.python.org/pypi/{{ project_name_formatted }}) ## Overview -{% if add_c_abi %} +{%- if add_c_abi %} + ## C ABI `rust/capi` builds `lib{{ module }}_capi`, a C ABI over the Rust crate with the @@ -22,7 +23,7 @@ projects build against the installed wheel with `{{ module }}.get_include()`, `bundled` (the default, for wheels), `external` (a prebuilt library found through `HATCH_RS_LIBRARY_ROOT`, pkg-config, or the conda prefix), or `direct` (compile the crate in). -{% endif %} +{%- endif %} > [!NOTE] > This library was generated using [copier](https://copier.readthedocs.io/en/stable/) from the [Base Python Project Template repository](https://github.com/python-project-templates/base). From bba6bb21cd1a49ed9840750a2412812607ccd599 Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:29:17 -0500 Subject: [PATCH 3/4] Keep wheel artifacts list unindented without add_c_abi Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- python/rust/pyproject.toml.jinja | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/rust/pyproject.toml.jinja b/python/rust/pyproject.toml.jinja index 7961d0d..ff69581 100644 --- a/python/rust/pyproject.toml.jinja +++ b/python/rust/pyproject.toml.jinja @@ -217,10 +217,10 @@ artifacts = [ "{{ module }}/*.dll", "{{ module }}/*.dylib", "{{ module }}/*.so", - {% if add_c_abi -%} +{%- if add_c_abi %} "{{ module }}/include/**/*.h", "{{ module }}/lib/*", - {% endif -%} +{%- endif %} ] packages = [ "{{ module }}", From 5808c452704702ab8b3ad115e940fb978baffbb0 Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:30:42 -0500 Subject: [PATCH 4/4] Keep the rust Cargo.toml template ending as on main Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- python/rust/rust/Cargo.toml.jinja | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/python/rust/rust/Cargo.toml.jinja b/python/rust/rust/Cargo.toml.jinja index 43c3ba3..c03adbf 100644 --- a/python/rust/rust/Cargo.toml.jinja +++ b/python/rust/rust/Cargo.toml.jinja @@ -14,11 +14,10 @@ path = "src/lib.rs" crate-type = ["rlib"] [dependencies] -{%- if add_c_abi %} - +{% if add_c_abi %} [workspace] members = [ ".", "capi", ] -{%- endif %} +{% endif %}