Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ jobs:
- site-sveltekit
- site-webawesome
os:
- ubuntu-latest
- ubuntu-24.04
- macos-latest
exclude:
- template: uitk-svelte
Expand Down Expand Up @@ -84,8 +84,7 @@ jobs:
- name: Install clang-format
run: |
if [[ "$RUNNER_OS" == "Linux" ]]; then
sudo apt-get install -y clang-format-14
sudo ln -sf /usr/bin/clang-format-14 /usr/bin/clang-format
sudo apt-get install -y clang-format
elif [[ "$RUNNER_OS" == "macOS" ]]; then
brew install clang-format
fi
Expand Down
8 changes: 5 additions & 3 deletions python/rust/README.md.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
## 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
generated header `rust/capi/include/{{ module }}.h` and a hand-written C++ wrapper
`{{ module }}.hpp` beside it. Wheels ship the library under `{{ module }}/lib` and
both headers under `{{ module }}/include/{{ module }}`, and the Python extension
links against it rather than compiling the crate in. The tests compile a C and a
C++ program against the installed package to prove the wheel is consumable. Other
projects build against the installed wheel with `{{ module }}.get_include()`,
`get_library_dirs()`, `get_libraries()`, and `get_prefix()`.

Expand Down
11 changes: 10 additions & 1 deletion python/rust/pyproject.toml.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ repair-wheel-command = "delocate-wheel --require-archs {delocate_archs} --exclud
[tool.cibuildwheel.windows]
environment = {PATH="$UserProfile\\.cargo\bin;$PATH", CARGO_TERM_COLOR="always"}
skip = "*win32 *arm64"

{% if add_c_abi -%}
# The C ABI library ships inside the wheel; delvewheel must not look for it on PATH.
repair-wheel-command = "delvewheel repair --exclude {{ module }}_capi.dll -w {dest_dir} {wheel}"
{% endif %}
{% if add_pyodide -%}
[tool.cibuildwheel.pyodide]
test-command = "python -m pytest -vvv --pyargs {{ module }}.tests"
Expand Down Expand Up @@ -183,6 +186,11 @@ source = "rust/capi/include/{{ module }}.h"
destination = "{{ module }}/include/{{ module }}/{{ module }}.h"
install-scheme = "package"

[[tool.hatch.build.hooks.hatch-rs.artifacts.outputs]]
source = "rust/capi/include/{{ module }}.hpp"
destination = "{{ module }}/include/{{ module }}/{{ module }}.hpp"
install-scheme = "package"

# The PyO3 extension, linked against the library by default (library-source = bundled).
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
name = "{{ module }}"
Expand Down Expand Up @@ -219,6 +227,7 @@ artifacts = [
"{{ module }}/*.so",
{%- if add_c_abi %}
"{{ module }}/include/**/*.h",
"{{ module }}/include/**/*.hpp",
"{{ module }}/lib/*",
{%- endif %}
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// C++ wrapper over the C ABI in {{ module }}.h. Hand-written; shipped next to
// the generated header so C++ consumers of the wheel get RAII handles and
// exceptions instead of status checks.
#pragma once

#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>

#include "{{ module }}.h"

namespace {{ module }} {

/// The ABI version of the loaded library.
inline unsigned abi_version() { return {{ module }}_abi_version(); }

/// An example value owned by the library.
class Example {
public:
explicit Example(std::string_view value) : handle_({{ module }}_example_new(value.data(), value.size())) {
if (handle_ == nullptr) {
throw std::invalid_argument("{{ module }}_example_new rejected the value");
}
}
~Example() { {{ module }}_example_free(handle_); }
Example(const Example&) = delete;
Example& operator=(const Example&) = delete;
Example(Example&& other) noexcept : handle_(std::exchange(other.handle_, nullptr)) {}
Example& operator=(Example&& other) noexcept {
std::swap(handle_, other.handle_);
return *this;
}

/// The example's value.
std::string stuff() const {
char* raw = {{ module }}_example_stuff(handle_);
if (raw == nullptr) {
throw std::runtime_error("{{ module }}_example_stuff failed");
}
std::string value(raw);
{{ module }}_string_free(raw);
return value;
}

/// The underlying handle, still owned by this object.
{{ module }}_example* get() const noexcept { return handle_; }

private:
{{ module }}_example* handle_;
};

} // namespace {{ module }}
101 changes: 96 additions & 5 deletions python/rust/{{module}}/tests/test_all.py.jinja
Original file line number Diff line number Diff line change
@@ -1,29 +1,120 @@
{% if add_c_abi -%}
import os
from ctypes import CDLL, c_uint32
from pathlib import Path
from shutil import which
from subprocess import run
from sys import platform

import pytest

from {{ module }} import get_include, get_libraries, get_library_dirs
from {{ module }}.{{ module }} import Example

C_CONSUMER = """
#include <stdio.h>
#include <{{ module }}/{{ module }}.h>

int main(void) {
{{ module }}_example *example = {{ module }}_example_new("consumer", 8);
if (example == NULL) {
return 1;
}
char *stuff = {{ module }}_example_stuff(example);
printf("%u %s", {{ module }}_abi_version(), stuff);
{{ module }}_string_free(stuff);
{{ module }}_example_free(example);
return 0;
}
"""

CPP_CONSUMER = """
#include <iostream>
#include <{{ module }}/{{ module }}.hpp>

int main() {
{{ module }}::Example example("consumer");
std::cout << {{ module }}::abi_version() << " " << example.stuff();
return 0;
}
"""


def _library_filename(name: str) -> str:
return f"{name}.dll" if platform == "win32" else f"lib{name}.dylib" if platform == "darwin" else f"lib{name}.so"


def _compiler(language: str) -> str | None:
names = {"c": ("cc", "gcc", "clang", "cl"), "c++": ("c++", "g++", "clang++", "cl")}[language]
return next((path for path in map(which, names) if path), None)


def _build_and_run(tmp_path: Path, source: str, language: str) -> str:
"""Compiles a consumer against the installed package and returns its output."""
if platform == "emscripten":
pytest.skip("Pyodide wheels compile the library in")
compiler = _compiler(language)
if compiler is None:
pytest.skip(f"no {language} compiler on PATH")
(library,) = get_libraries()
(library_dir,) = get_library_dirs()
source_path = tmp_path / ("consumer.cpp" if language == "c++" else "consumer.c")
source_path.write_text(source)
executable = tmp_path / ("consumer.exe" if platform == "win32" else "consumer")
env = dict(os.environ)
if Path(compiler).stem.lower() == "cl":
command = [
compiler,
"/nologo",
"/EHsc",
f"/I{get_include()}",
str(source_path),
f"/Fe:{executable}",
"/link",
f"/LIBPATH:{library_dir}",
f"{library}.dll.lib",
]
env["PATH"] = library_dir + os.pathsep + env["PATH"]
else:
standard = ["-std=c++17"] if language == "c++" else []
command = [
compiler,
*standard,
f"-I{get_include()}",
str(source_path),
f"-L{library_dir}",
f"-l{library}",
f"-Wl,-rpath,{library_dir}",
"-o",
str(executable),
]
run(command, check=True, cwd=tmp_path)
return run([str(executable)], check=True, capture_output=True, text=True, env=env).stdout


def test_example_round_trips_through_the_library():
assert str(Example("test")) == "test"
assert repr(Example("test")) == "Example<test>"


def test_c_library_and_header_are_installed():
def test_c_library_and_headers_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()
include = Path(get_include()) / "{{ module }}"
assert "#define {{ module | upper }}_ABI_VERSION 1" in (include / "{{ module }}.h").read_text()
assert "class Example" in (include / "{{ module }}.hpp").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 = CDLL(str(Path(get_library_dirs()[0]) / _library_filename(name)))
library.{{ module }}_abi_version.restype = c_uint32
assert library.{{ module }}_abi_version() == 1


def test_c_consumer_builds_against_the_installed_package(tmp_path):
assert _build_and_run(tmp_path, C_CONSUMER, "c") == "1 consumer"


def test_cpp_consumer_builds_against_the_installed_package(tmp_path):
assert _build_and_run(tmp_path, CPP_CONSUMER, "c++") == "1 consumer"
{%- else -%}
from {{ module }}{% if add_pyodide %}.{{ module }} import Example{% else %} import *{% endif %}

Expand Down
Loading