From e6b1613d9855388e0cc9df86c4cecb7dec5e164f Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:00:48 -0500 Subject: [PATCH 1/4] Add a C ABI library option to the cppjswasm template add_c_abi now also applies to the cppjswasm template, with the layout the cpp template uses: cpp/ builds lib with an extern "C" surface, cpp/python holds the pybind11 extension that links it through hatch-cpp depends, and cpp/CMakeLists.txt builds and installs the library without Python. The JavaScript build is unchanged and still compiles the C++ sources with Emscripten. This template binds a class, so the C ABI has an opaque handle for Example with create, free, and accessor functions, and the extension wraps the handle. The C API definitions are excluded from clang-format because their line breaks would depend on the module name's length. extension_cpp.pyi now declares Example, which the extension already exported. A cppjswasm-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 | 9 +- Makefile | 17 ++- README.md | 2 +- copier.yaml | 2 +- examples/cppjswasm-capi.yaml | 13 ++ examples/cppjswasm.yaml | 1 + python/cppjswasm/README.md.jinja | 26 ++++ ...dd_c_abi %}CMakeLists.txt{% endif %}.jinja | 46 +++++++ .../{{module}}.pc.in.jinja | 9 ++ .../{{module}}Config.cmake.in.jinja | 4 + .../extension.cpp.jinja | 46 +++++++ ... if add_c_abi %}c_api.cpp{% endif %}.jinja | 50 ++++++++ ...dd_c_abi %}extension.cpp{% endif %}.jinja} | 0 python/cppjswasm/pyproject.toml.jinja | 52 +++++++- python/cppjswasm/{{module}}/__init__.py | 18 --- python/cppjswasm/{{module}}/__init__.py.jinja | 46 +++++++ python/cppjswasm/{{module}}/extension_cpp.pyi | 5 + .../{{module}}/tests/test_all.py.jinja | 117 ++++++++++++++++++ .../{{module}}/{{module}}.h.jinja | 44 +++++++ 19 files changed, 476 insertions(+), 31 deletions(-) create mode 100644 examples/cppjswasm-capi.yaml create mode 100644 python/cppjswasm/cpp/{% if add_c_abi %}CMakeLists.txt{% endif %}.jinja create mode 100644 python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}.pc.in.jinja create mode 100644 python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}Config.cmake.in.jinja create mode 100644 python/cppjswasm/cpp/{% if add_c_abi %}python{% endif %}/extension.cpp.jinja create mode 100644 python/cppjswasm/cpp/{{project_name_formatted}}/{% if add_c_abi %}c_api.cpp{% endif %}.jinja rename python/cppjswasm/cpp/{{project_name_formatted}}/{extension.cpp.jinja => {% if not add_c_abi %}extension.cpp{% endif %}.jinja} (100%) delete mode 100644 python/cppjswasm/{{module}}/__init__.py create mode 100644 python/cppjswasm/{{module}}/__init__.py.jinja create mode 100644 python/cppjswasm/{{module}}/{% if add_c_abi %}include{% endif %}/{{module}}/{{module}}.h.jinja diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 9dd580e..d8d1b98 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -34,6 +34,7 @@ jobs: - rust-capi - rustjswasm - cppjswasm + - cppjswasm-capi - uitk-svelte - uitk-webawesome - site-react @@ -89,7 +90,7 @@ jobs: elif [[ "$RUNNER_OS" == "macOS" ]]; then brew install clang-format fi - if: matrix.template == 'cpp' || matrix.template == 'cpp-capi' || matrix.template == 'cppjswasm' + if: matrix.template == 'cpp' || matrix.template == 'cpp-capi' || matrix.template == 'cppjswasm' || matrix.template == 'cppjswasm-capi' - name: Setup Node.js uses: actions-ext/node/setup@8bcebee998923fcc26f5854b4fd05ea378b58262 @@ -97,7 +98,7 @@ jobs: version: 22.x pnpm_version: 11.11.0 js_folder: "." - if: matrix.template == 'js' || matrix.template == 'jupyter' || matrix.template == 'cppjswasm' || matrix.template == 'rustjswasm' || matrix.template == 'uitk-svelte' || matrix.template == 'uitk-webawesome' || matrix.template == 'site-react' || matrix.template == 'site-sveltekit' || matrix.template == 'site-webawesome' + if: matrix.template == 'js' || matrix.template == 'jupyter' || matrix.template == 'cppjswasm' || matrix.template == 'cppjswasm-capi' || matrix.template == 'rustjswasm' || matrix.template == 'uitk-svelte' || matrix.template == 'uitk-webawesome' || matrix.template == 'site-react' || matrix.template == 'site-sveltekit' || matrix.template == 'site-webawesome' - name: Setup Rust uses: actions-ext/rust/setup@af6343171cd1a86c4183da96de7eb96e15599662 @@ -105,7 +106,7 @@ jobs: - name: Install JavaScript dependencies run: pnpm install - if: matrix.template == 'js' || matrix.template == 'jupyter' || matrix.template == 'cppjswasm' || matrix.template == 'rustjswasm' + if: matrix.template == 'js' || matrix.template == 'jupyter' || matrix.template == 'cppjswasm' || matrix.template == 'cppjswasm-capi' || matrix.template == 'rustjswasm' - name: Build Rust fixture run: cargo build @@ -134,4 +135,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 == 'cpp-capi' || matrix.template == 'cppjswasm' || matrix.template == 'rust' || matrix.template == 'rust-capi' || matrix.template == 'rustjswasm' + if: matrix.template == 'cpp' || matrix.template == 'cpp-capi' || matrix.template == 'cppjswasm' || matrix.template == 'cppjswasm-capi' || matrix.template == 'rust' || matrix.template == 'rust-capi' || matrix.template == 'rustjswasm' diff --git a/Makefile b/Makefile index 02991d5..21dc02b 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-cpp-capi 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 +.PHONY: gen-python gen-cpp gen-cpp-capi gen-js gen-jupyter gen-rust gen-rust-capi gen-rustjswasm gen-cppjswasm gen-cppjswasm-capi 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 @@ -87,6 +87,11 @@ gen-cppjswasm: ## regenerate the cppjswasm template from scratch copier copy -w . ../python-template-cppjswasm --data-file examples/cppjswasm.yaml cd ../python-template-cppjswasm && $(SED) 's#_src_path: .#_src_path: https://github.com/python-project-templates/base.git#g' ./.copier-answers.yaml +gen-cppjswasm-capi: ## regenerate the cppjswasm template with a C ABI library from scratch + mkdir -p ../python-template-cppjswasm-capi && cd ../python-template-cppjswasm-capi && rm -rf ./* && rm -rf .copier-answers.yaml .gitignore .github .gitattributes + copier copy -w . ../python-template-cppjswasm-capi --data-file examples/cppjswasm-capi.yaml + cd ../python-template-cppjswasm-capi && $(SED) 's#_src_path: .#_src_path: https://github.com/python-project-templates/base.git#g' ./.copier-answers.yaml + gen-uitk-svelte: ## regenerate the Svelte UI toolkit template from scratch mkdir -p ../javascript-template-uitk-svelte && cd ../javascript-template-uitk-svelte && rm -rf ./* && rm -rf .copier-answers.yaml .github .gitignore .prettierignore .prettierrc .oxfmtrc.json .oxlintrc.json copier copy -w . ../javascript-template-uitk-svelte --data-file examples/uitk-svelte.yaml @@ -107,7 +112,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-cpp-capi 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 +.PHONY: test-python test-cpp test-cpp-capi test-js test-jupyter test-rust test-rust-capi test-rustjswasm test-cppjswasm-capi 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 @@ -178,6 +183,14 @@ test-cppjswasm: cd ../python-template-cppjswasm && make checks cd ../python-template-cppjswasm && make test +test-cppjswasm-capi: + cd ../python-template-cppjswasm-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-cppjswasm-capi && make develop + cd ../python-template-cppjswasm-capi && git add js/pnpm-lock.yaml && git commit -m "lockfile" + cd ../python-template-cppjswasm-capi && make lint + cd ../python-template-cppjswasm-capi && make checks + cd ../python-template-cppjswasm-capi && make test + test-uitk-svelte: cd ../javascript-template-uitk-svelte && pnpm install cd ../javascript-template-uitk-svelte && pnpm exec playwright install chromium diff --git a/README.md b/README.md index 9850840..4b9d3cf 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ One selector chooses a template: - `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/`. +- `Python / C++ + JavaScript + WebAssembly` generates a C++ package with Python and WebAssembly bindings from `python/cppjswasm/`. `add_c_abi` adds the same C ABI library for the Python extension. - `JavaScript / UI Toolkit / Svelte` generates a Svelte package with shared design tokens, components, and a demo app from `javascript/uitk-svelte/`. - `JavaScript / UI Toolkit / Lit + Web Awesome` generates Lit custom elements with Web Awesome, shared design tokens, and a demo app from `javascript/uitk-webawesome/`. - `JavaScript / Site / React` generates a React site with Vite, Vitest, and Playwright from `javascript/site-react/`. diff --git a/copier.yaml b/copier.yaml index 85b7806..4284dcc 100644 --- a/copier.yaml +++ b/copier.yaml @@ -85,7 +85,7 @@ add_c_abi: type: bool default: false help: Build a C ABI library that the Python extension links against - when: "{{ add_extension in ['cpp', 'rust'] }}" + when: "{{ add_extension in ['cpp', 'cppjswasm', 'rust'] }}" python_version_primary: type: str diff --git a/examples/cppjswasm-capi.yaml b/examples/cppjswasm-capi.yaml new file mode 100644 index 0000000..81060cd --- /dev/null +++ b/examples/cppjswasm-capi.yaml @@ -0,0 +1,13 @@ +--- +add_c_abi: true +add_docs: true +add_pyodide: false +add_vcpkg: false +add_wiki: true +add_extension: cppjswasm +email: 3105306+timkpaine@users.noreply.github.com +github: python-project-templates +project_description: A C++-JavaScript-Python project template with a C ABI library +project_name: python template cppjswasm capi +python_version_primary: '3.11' +team: Python Project Template Authors diff --git a/examples/cppjswasm.yaml b/examples/cppjswasm.yaml index bbc3b06..d59f072 100644 --- a/examples/cppjswasm.yaml +++ b/examples/cppjswasm.yaml @@ -1,4 +1,5 @@ --- +add_c_abi: false add_docs: true add_pyodide: false add_vcpkg: true diff --git a/python/cppjswasm/README.md.jinja b/python/cppjswasm/README.md.jinja index 7e11b1c..6cba8fb 100644 --- a/python/cppjswasm/README.md.jinja +++ b/python/cppjswasm/README.md.jinja @@ -8,6 +8,32 @@ [![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 + +`cpp/{{ project_name_formatted }}` builds `lib{{ module }}`, a C ABI over the C++ code, declared in +`{{ module }}/include/{{ module }}/{{ module }}.h`. Wheels ship the library under `{{ module }}/lib` and +the header under `{{ module }}/include/{{ module }}`, and the pybind11 extension in `cpp/python` links +against the library. The JavaScript build compiles the C++ sources with Emscripten and does not +use the C ABI. The tests compile a C program against the installed package. Other +projects build against the installed wheel with `{{ module }}.get_include()`, +`get_library_dirs()`, `get_libraries()`, and `get_prefix()`. + +`HATCH_CPP_LIBRARY_SOURCE` chooses where the library comes from at build time: +`bundled` (the default, for wheels), `external` (a prebuilt library found +through `HATCH_CPP_LIBRARY_ROOT`, pkg-config, or the conda prefix), or `direct` +(compile the library sources into the extension). + +`cpp/CMakeLists.txt` builds and installs the library without Python, with a CMake +package config and a pkg-config file, for conda, vcpkg, and system packages: + +```bash +cmake -S cpp -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build +cmake --install build --prefix /path/to/prefix +``` +{%- 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/cppjswasm/cpp/{% if add_c_abi %}CMakeLists.txt{% endif %}.jinja b/python/cppjswasm/cpp/{% if add_c_abi %}CMakeLists.txt{% endif %}.jinja new file mode 100644 index 0000000..0db29f8 --- /dev/null +++ b/python/cppjswasm/cpp/{% if add_c_abi %}CMakeLists.txt{% endif %}.jinja @@ -0,0 +1,46 @@ +# Builds and installs lib{{ module }} without Python, for conda, vcpkg, and system packages. +cmake_minimum_required(VERSION 3.20) +project({{ module }} VERSION 0.1.0 LANGUAGES CXX) + +include(CMakePackageConfigHelpers) + +add_library({{ module }} SHARED {{ project_name_formatted }}/c_api.cpp {{ project_name_formatted }}/example.cpp) +add_library({{ module }}::{{ module }} ALIAS {{ module }}) +target_compile_features({{ module }} PRIVATE cxx_std_17) +target_compile_definitions({{ module }} PRIVATE {{ module | upper }}_BUILD) +target_include_directories( + {{ module }} + PUBLIC $ $ + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} +) +# SOVERSION is {{ module | upper }}_ABI_VERSION. +set_target_properties( + {{ module }} + PROPERTIES VERSION ${PROJECT_VERSION} + SOVERSION 1 + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + INSTALL_NAME_DIR "@rpath" +) + +install( + TARGETS {{ module }} + EXPORT {{ module }}Targets + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib +) +install(DIRECTORY ../{{ module }}/include/ DESTINATION include) +install(EXPORT {{ module }}Targets NAMESPACE {{ module }}:: DESTINATION lib/cmake/{{ module }}) + +configure_package_config_file( + cmake/{{ module }}Config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/{{ module }}Config.cmake + INSTALL_DESTINATION lib/cmake/{{ module }} +) +write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/{{ module }}ConfigVersion.cmake COMPATIBILITY SameMinorVersion) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/{{ module }}Config.cmake ${CMAKE_CURRENT_BINARY_DIR}/{{ module }}ConfigVersion.cmake + DESTINATION lib/cmake/{{ module }} +) + +configure_file(cmake/{{ module }}.pc.in ${CMAKE_CURRENT_BINARY_DIR}/{{ module }}.pc @ONLY) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/{{ module }}.pc DESTINATION lib/pkgconfig) diff --git a/python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}.pc.in.jinja b/python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}.pc.in.jinja new file mode 100644 index 0000000..fba91bb --- /dev/null +++ b/python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}.pc.in.jinja @@ -0,0 +1,9 @@ +prefix=${pcfiledir}/../.. +libdir=${prefix}/lib +includedir=${prefix}/include + +Name: {{ module }} +Description: {{ project_description }} +Version: @PROJECT_VERSION@ +Libs: -L${libdir} -l{{ module }} +Cflags: -I${includedir} diff --git a/python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}Config.cmake.in.jinja b/python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}Config.cmake.in.jinja new file mode 100644 index 0000000..d9edb54 --- /dev/null +++ b/python/cppjswasm/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}Config.cmake.in.jinja @@ -0,0 +1,4 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/{{ module }}Targets.cmake") +check_required_components({{ module }}) diff --git a/python/cppjswasm/cpp/{% if add_c_abi %}python{% endif %}/extension.cpp.jinja b/python/cppjswasm/cpp/{% if add_c_abi %}python{% endif %}/extension.cpp.jinja new file mode 100644 index 0000000..01cd66d --- /dev/null +++ b/python/cppjswasm/cpp/{% if add_c_abi %}python{% endif %}/extension.cpp.jinja @@ -0,0 +1,46 @@ +#include +#include +#include + +#include "{{ module }}/{{ module }}.h" + +namespace py = pybind11; + +namespace { + +// Owns an example in lib{{ module }} through the C ABI. +class Example { +public: + explicit Example(const std::string& value) + : handle({{ module }}_example_new(value.c_str())) { + if(handle == nullptr) + throw std::runtime_error("{{ module }}_example_new failed"); + } + ~Example() { {{ module }}_example_free(handle); } + Example(const Example&) = delete; + Example& operator=(const Example&) = delete; + + std::string stuff() const { return {{ module }}_example_stuff(handle); } + + void set_stuff(const std::string& value) { + if({{ module }}_example_set_stuff(handle, value.c_str()) != 0) + throw std::runtime_error("{{ module }}_example_set_stuff failed"); + } + +private: + {{ module }}_example* handle; +}; + +} + +PYBIND11_MODULE(extension_cpp, m) { + m.doc() = "pybind11 extension module"; + + m.def("add", &{{ module }}_add, "A function that adds two numbers"); + + py::class_(m, "Example") + .def(py::init()) + .def_property("stuff", &Example::stuff, &Example::set_stuff) + .def("__str__", [](const Example& e) { return e.stuff(); }) + .def("__repr__", [](const Example& e) { return std::string("Example<") + e.stuff() + ">"; }); +} diff --git a/python/cppjswasm/cpp/{{project_name_formatted}}/{% if add_c_abi %}c_api.cpp{% endif %}.jinja b/python/cppjswasm/cpp/{{project_name_formatted}}/{% if add_c_abi %}c_api.cpp{% endif %}.jinja new file mode 100644 index 0000000..0d7e6aa --- /dev/null +++ b/python/cppjswasm/cpp/{{project_name_formatted}}/{% if add_c_abi %}c_api.cpp{% endif %}.jinja @@ -0,0 +1,50 @@ +#include "{{ module }}/{{ module }}.h" + +#include "{{ project_name_formatted }}/example.hpp" + +struct {{ module }}_example { + Example value; +}; + +// The function names contain the module name, so clang-format would break these lines differently for each project. +// clang-format off + +uint32_t {{ module }}_abi_version(void) { + return {{ module | upper }}_ABI_VERSION; +} + +int32_t {{ module }}_add(int32_t i, int32_t j) { + return add(i, j); +} + +// Exceptions must not cross the C boundary, so each function that allocates reports failure through its return value. +{{ module }}_example* {{ module }}_example_new(const char* value) { + if(value == nullptr) + return nullptr; + try { + return new {{ module }}_example{Example(value)}; + } catch(...) { + return nullptr; + } +} + +void {{ module }}_example_free({{ module }}_example* example) { + delete example; +} + +const char* {{ module }}_example_stuff(const {{ module }}_example* example) { + return example->value.stuff.c_str(); +} + +int32_t {{ module }}_example_set_stuff({{ module }}_example* example, const char* value) { + if(value == nullptr) + return -1; + try { + example->value.stuff = value; + return 0; + } catch(...) { + return -1; + } +} + +// clang-format on diff --git a/python/cppjswasm/cpp/{{project_name_formatted}}/extension.cpp.jinja b/python/cppjswasm/cpp/{{project_name_formatted}}/{% if not add_c_abi %}extension.cpp{% endif %}.jinja similarity index 100% rename from python/cppjswasm/cpp/{{project_name_formatted}}/extension.cpp.jinja rename to python/cppjswasm/cpp/{{project_name_formatted}}/{% if not add_c_abi %}extension.cpp{% endif %}.jinja diff --git a/python/cppjswasm/pyproject.toml.jinja b/python/cppjswasm/pyproject.toml.jinja index 68df5e2..06dbd38 100644 --- a/python/cppjswasm/pyproject.toml.jinja +++ b/python/cppjswasm/pyproject.toml.jinja @@ -1,7 +1,7 @@ [build-system] requires = [ "hatchling", - "hatch-cpp{% if add_pyodide %}>=0.5.0{% endif %}", + "hatch-cpp{% if add_c_abi %}>=0.6.0{% elif add_pyodide %}>=0.5.0{% endif %}", "hatch-js", "pybind11", ] @@ -48,7 +48,7 @@ develop = [ "check-dist", "cibuildwheel", "codespell", - "hatch-cpp{% if add_pyodide %}>=0.5.0{% endif %}", + "hatch-cpp{% if add_c_abi %}>=0.6.0{% elif add_pyodide %}>=0.5.0{% endif %}", "hatch-js", "hatchling", "pybind11", @@ -94,7 +94,12 @@ replace = 'version = "{new_version}"' filename = "js/package.json" search = '"version": "{current_version}"' replace = '"version": "{new_version}"' - +{% if add_c_abi %} +[[tool.bumpversion.files]] +filename = "cpp/CMakeLists.txt" +search = "VERSION {current_version}" +replace = "VERSION {new_version}" +{% endif %} [tool.cibuildwheel] build = "cp{{ python_version_primary.replace('.', '') }}-*" test-command = "pytest -vvv {project}/{{ module }}/tests" @@ -103,18 +108,28 @@ test-extras = "develop" [tool.cibuildwheel.linux] environment = {SKIP_HATCH_JS="1"} 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 }}.so' -w {dest_dir} {wheel}" +{% endif %} [tool.cibuildwheel.macos] environment = {MACOSX_DEPLOYMENT_TARGET="11.0", SKIP_HATCH_JS="1"} archs = "arm64" - +{% if add_c_abi -%} +repair-wheel-command = "delocate-wheel --require-archs {delocate_archs} --exclude lib{{ module }}.dylib -w {dest_dir} -v {wheel}" +{% endif %} [tool.cibuildwheel.windows] environment = {SKIP_HATCH_JS="1"} skip = "*win32 *arm64" {% if add_pyodide -%} [tool.cibuildwheel.pyodide] +{% if add_c_abi -%} +# Emscripten has no shared libraries to split; compile the library in. +environment = {SKIP_HATCH_JS="1", HATCH_CPP_LIBRARY_SOURCE="direct"} +{% else -%} environment = {SKIP_HATCH_JS="1"} +{% endif -%} test-command = "python -m pytest -vvv --pyargs {{ module }}.tests" test-extras = [] test-requires = ["pytest"] @@ -152,9 +167,33 @@ targets = [ [tool.hatch.build.hooks.hatch-cpp] verbose = true +{%- if add_c_abi %} + +# lib{{ module }}: the C ABI library, shipped under {{ module }}/lib. Its header is in {{ module }}/include. +[[tool.hatch.build.hooks.hatch-cpp.libraries]] +name = "{{ module }}/lib/lib{{ module }}" +sources = ["cpp/{{ project_name_formatted }}/c_api.cpp", "cpp/{{ project_name_formatted }}/example.cpp"] +include-dirs = ["cpp", "{{ module }}/include"] +binding = "generic" +define-macros = ["{{ module | upper }}_BUILD"] +extra-compile-args-linux = ["-fvisibility=hidden"] +extra-compile-args-darwin = ["-fvisibility=hidden"] +expected-headers = ["{{ module }}/include/{{ module }}/{{ module }}.h"] +header-symbol-prefix = "{{ module }}_" +expected-abi-strings = ["{{ module | upper }}_ABI_VERSION 1"] + +# The pybind11 extension, linked against the library by default (library-source = bundled). +[[tool.hatch.build.hooks.hatch-cpp.libraries]] +name = "{{ module }}/extension_cpp" +sources = ["cpp/python/extension.cpp"] +include-dirs = ["{{ module }}/include"] +binding = "pybind11" +depends = ["{{ module }}/lib/lib{{ module }}"] +{%- else %} libraries = [ {name = "{{ module }}/extension_cpp", sources = ["cpp/{{ project_name_formatted }}/example.cpp", "cpp/{{ project_name_formatted }}/extension.cpp"], include-dirs = ["cpp"], binding="pybind11"} ] +{%- endif %} [tool.hatch.build.targets.sdist] exclude = ["*.dll", "*.dylib", "*.so", "*.pyd"] @@ -175,6 +214,9 @@ artifacts = [ "{{ module }}/*.dylib", "{{ module }}/*.so", "{{ module }}/extension", +{%- if add_c_abi %} + "{{ module }}/lib/*", +{%- endif %} ] packages = [ "{{ module }}", diff --git a/python/cppjswasm/{{module}}/__init__.py b/python/cppjswasm/{{module}}/__init__.py deleted file mode 100644 index 6fc0df2..0000000 --- a/python/cppjswasm/{{module}}/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -import os -import os.path - -from .extension_cpp import * - -__version__ = "0.1.0" - - -def include_path(): - return os.path.abspath(os.path.join(os.path.dirname(__file__), "include")) - - -def bin_path(): - return os.path.abspath(os.path.join(os.path.dirname(__file__), "bin")) - - -def lib_path(): - return os.path.abspath(os.path.join(os.path.dirname(__file__), "lib")) diff --git a/python/cppjswasm/{{module}}/__init__.py.jinja b/python/cppjswasm/{{module}}/__init__.py.jinja new file mode 100644 index 0000000..f8da490 --- /dev/null +++ b/python/cppjswasm/{{module}}/__init__.py.jinja @@ -0,0 +1,46 @@ +import os +import os.path +{%- if add_c_abi %} + +if os.name == "nt" and os.path.isdir(os.path.join(os.path.dirname(__file__), "lib")): + # Windows has no rpath, so the extension finds lib{{ module }}.dll through this directory. + _DLL_DIRECTORY = os.add_dll_directory(os.path.join(os.path.dirname(__file__), "lib")) +{%- endif %} + +from .extension_cpp import * + +__version__ = "0.1.0" + + +def include_path(): + return os.path.abspath(os.path.join(os.path.dirname(__file__), "include")) + + +def bin_path(): + return os.path.abspath(os.path.join(os.path.dirname(__file__), "bin")) + + +def lib_path(): + return os.path.abspath(os.path.join(os.path.dirname(__file__), "lib")) +{%- if add_c_abi %} + + +def get_prefix() -> str: + """The installed package directory, which holds ``include`` and ``lib`` for lib{{ module }}.""" + return os.path.abspath(os.path.dirname(__file__)) + + +def get_include() -> str: + """The directory holding ``{{ module }}/{{ module }}.h``.""" + return include_path() + + +def get_library_dirs() -> list[str]: + """Directories holding the bundled lib{{ module }} shared library.""" + return [lib_path()] + + +def get_libraries() -> list[str]: + """Link names for lib{{ module }}, for ``-l`` or ``target_link_libraries``.""" + return ["lib{{ module }}" if os.name == "nt" else "{{ module }}"] +{%- endif %} diff --git a/python/cppjswasm/{{module}}/extension_cpp.pyi b/python/cppjswasm/{{module}}/extension_cpp.pyi index bfb558d..1ee466e 100644 --- a/python/cppjswasm/{{module}}/extension_cpp.pyi +++ b/python/cppjswasm/{{module}}/extension_cpp.pyi @@ -1 +1,6 @@ +class Example: + stuff: str + + def __init__(self, value: str) -> None: ... + def add(i: int, j: int) -> int: ... diff --git a/python/cppjswasm/{{module}}/tests/test_all.py.jinja b/python/cppjswasm/{{module}}/tests/test_all.py.jinja index f3a6ba9..07f26a0 100644 --- a/python/cppjswasm/{{module}}/tests/test_all.py.jinja +++ b/python/cppjswasm/{{module}}/tests/test_all.py.jinja @@ -1,6 +1,123 @@ +{% 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 Example, add, get_include, get_libraries, get_library_dirs + +C_CONSUMER = """ +#include +#include <{{ module }}/{{ module }}.h> + +int main(void) { + {{ module }}_example *example = {{ module }}_example_new("consumer"); + if (example == NULL) { + return 1; + } + printf("%u %d %s", {{ module }}_abi_version(), {{ module }}_add(1, 2), {{ module }}_example_stuff(example)); + {{ module }}_example_free(example); + return 0; +} +""" + +CMAKE_CONSUMER = """ +cmake_minimum_required(VERSION 3.20) +project(consumer LANGUAGES C) +find_package({{ module }} CONFIG REQUIRED) +add_executable(consumer consumer.c) +target_link_libraries(consumer PRIVATE {{ module }}::{{ module }}) +""" + + +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 _cmake_build(cmake: str, source: Path, build: Path, option: str) -> None: + run([cmake, "-S", str(source), "-B", str(build), option, "-DCMAKE_BUILD_TYPE=Release"], check=True) + run([cmake, "--build", str(build), "--config", "Release"], check=True) + + +def test_all(): + assert 3 == add(1, 2) + + +def test_example_round_trips_through_the_library(): + example = Example("test") + assert str(example) == "test" + example.stuff = "changed" + assert repr(example) == "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() + 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): + if platform == "emscripten": + pytest.skip("Pyodide wheels compile the library in") + compiler = next((path for path in map(which, ("cc", "gcc", "clang", "cl")) if path), None) + if compiler is None: + pytest.skip("no C compiler on PATH") + (library,) = get_libraries() + (library_dir,) = get_library_dirs() + source = tmp_path / "consumer.c" + source.write_text(C_CONSUMER) + executable = tmp_path / ("consumer.exe" if platform == "win32" else "consumer") + env = dict(os.environ) + if Path(compiler).stem.lower() == "cl": + command = [compiler, "/nologo", f"/I{get_include()}", str(source), f"/Fe:{executable}", "/link", f"/LIBPATH:{library_dir}", f"{library}.lib"] + env["PATH"] = library_dir + os.pathsep + env["PATH"] + else: + command = [ + compiler, + f"-I{get_include()}", + str(source), + f"-L{library_dir}", + f"-l{library}", + f"-Wl,-rpath,{library_dir}", + "-o", + str(executable), + ] + run(command, check=True, cwd=tmp_path) + assert run([str(executable)], check=True, capture_output=True, text=True, env=env).stdout == "1 3 consumer" + + +def test_cmake_project_installs_a_package_that_find_package_locates(tmp_path): + cmake = which("cmake") + project = Path(__file__).resolve().parents[2] / "cpp" + if cmake is None or not (project / "CMakeLists.txt").is_file(): + pytest.skip("needs cmake and the source tree") + prefix = tmp_path / "prefix" + _cmake_build(cmake, project, tmp_path / "build", f"-DCMAKE_INSTALL_PREFIX={prefix}") + run([cmake, "--install", str(tmp_path / "build"), "--config", "Release"], check=True) + assert (prefix / "lib" / "pkgconfig" / "{{ module }}.pc").is_file() + + consumer = tmp_path / "consumer" + consumer.mkdir() + (consumer / "CMakeLists.txt").write_text(CMAKE_CONSUMER) + (consumer / "consumer.c").write_text(C_CONSUMER) + _cmake_build(cmake, consumer, consumer / "build", f"-DCMAKE_PREFIX_PATH={prefix}") + (executable,) = [path for path in (consumer / "build").rglob("consumer*") if path.name in ("consumer", "consumer.exe") and path.is_file()] + env = {**os.environ, "PATH": str(prefix / "bin") + os.pathsep + os.environ["PATH"]} + assert run([str(executable)], check=True, capture_output=True, text=True, env=env).stdout == "1 3 consumer" +{%- else -%} from {{ module }} import add class TestAll: def test_all(self): assert 3 == add(1, 2) +{%- endif %} diff --git a/python/cppjswasm/{{module}}/{% if add_c_abi %}include{% endif %}/{{module}}/{{module}}.h.jinja b/python/cppjswasm/{{module}}/{% if add_c_abi %}include{% endif %}/{{module}}/{{module}}.h.jinja new file mode 100644 index 0000000..9eb9f81 --- /dev/null +++ b/python/cppjswasm/{{module}}/{% if add_c_abi %}include{% endif %}/{{module}}/{{module}}.h.jinja @@ -0,0 +1,44 @@ +/* C ABI of lib{{ module }}. Every exported function is declared here. */ +#pragma once + +#include + +#define {{ module | upper }}_ABI_VERSION 1 + +#if defined(_WIN32) && defined({{ module | upper }}_BUILD) +#define {{ module | upper }}_API __declspec(dllexport) +#elif defined(_WIN32) +#define {{ module | upper }}_API __declspec(dllimport) +#else +#define {{ module | upper }}_API __attribute__((visibility("default"))) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* An example value owned by the library. */ +typedef struct {{ module }}_example {{ module }}_example; + +/* The ABI version the library was built with. Compare it with {{ module | upper }}_ABI_VERSION. */ +{{ module | upper }}_API uint32_t {{ module }}_abi_version(void); + +/* Adds two numbers. */ +{{ module | upper }}_API int32_t {{ module }}_add(int32_t i, int32_t j); + +/* Creates an example holding a copy of value. Returns NULL if value is NULL or allocation fails. + Free the result with {{ module }}_example_free. */ +{{ module | upper }}_API {{ module }}_example* {{ module }}_example_new(const char* value); + +/* Frees an example. NULL is ignored. */ +{{ module | upper }}_API void {{ module }}_example_free({{ module }}_example* example); + +/* The example's value. The pointer is valid until the example is changed or freed. */ +{{ module | upper }}_API const char* {{ module }}_example_stuff(const {{ module }}_example* example); + +/* Replaces the example's value with a copy of value. Returns 0 on success and -1 on failure. */ +{{ module | upper }}_API int32_t {{ module }}_example_set_stuff({{ module }}_example* example, const char* value); + +#ifdef __cplusplus +} +#endif From 4c6e0a6b8866ddce2ebffb5cd4210658327ce14b Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:06:34 -0500 Subject: [PATCH 2/4] Set PATH for the Windows consumer program with any compiler Windows runners find MinGW gcc before cl, and the program needs the library directory on PATH either way. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- python/cppjswasm/{{module}}/tests/test_all.py.jinja | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/cppjswasm/{{module}}/tests/test_all.py.jinja b/python/cppjswasm/{{module}}/tests/test_all.py.jinja index 07f26a0..207bdf5 100644 --- a/python/cppjswasm/{{module}}/tests/test_all.py.jinja +++ b/python/cppjswasm/{{module}}/tests/test_all.py.jinja @@ -77,9 +77,11 @@ def test_c_consumer_builds_against_the_installed_package(tmp_path): source.write_text(C_CONSUMER) executable = tmp_path / ("consumer.exe" if platform == "win32" else "consumer") env = dict(os.environ) + if platform == "win32": + # Windows has no rpath, so the program finds the DLL through PATH whichever compiler built it. + env["PATH"] = library_dir + os.pathsep + env["PATH"] if Path(compiler).stem.lower() == "cl": command = [compiler, "/nologo", f"/I{get_include()}", str(source), f"/Fe:{executable}", "/link", f"/LIBPATH:{library_dir}", f"{library}.lib"] - env["PATH"] = library_dir + os.pathsep + env["PATH"] else: command = [ compiler, From 4672c139b984825b6e5b7e681253109444c3d92f Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:11:55 -0500 Subject: [PATCH 3/4] Exclude the C ABI library from delvewheel repair cibuildwheel runs delvewheel on Windows by default, and it cannot find the DLL the wheel already ships. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- python/cppjswasm/pyproject.toml.jinja | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/python/cppjswasm/pyproject.toml.jinja b/python/cppjswasm/pyproject.toml.jinja index 06dbd38..09c1b5f 100644 --- a/python/cppjswasm/pyproject.toml.jinja +++ b/python/cppjswasm/pyproject.toml.jinja @@ -121,7 +121,10 @@ repair-wheel-command = "delocate-wheel --require-archs {delocate_archs} --exclud [tool.cibuildwheel.windows] environment = {SKIP_HATCH_JS="1"} 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 lib{{ module }}.dll -w {dest_dir} {wheel}" +{% endif %} {% if add_pyodide -%} [tool.cibuildwheel.pyodide] {% if add_c_abi -%} From 4ba78d79cca24db83556184ee1d13361b0a479e6 Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:25:32 -0500 Subject: [PATCH 4/4] Keep the JS build script formatted for longer module names build.mjs repeated the extension path, which contains the module name, so oxfmt wrapped two calls once the name passed 25 characters and pnpm lint failed for the cppjswasm-capi example. The path is now a constant. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- python/cppjswasm/js/build.mjs.jinja | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/python/cppjswasm/js/build.mjs.jinja b/python/cppjswasm/js/build.mjs.jinja index c63b912..17beb61 100644 --- a/python/cppjswasm/js/build.mjs.jinja +++ b/python/cppjswasm/js/build.mjs.jinja @@ -5,6 +5,8 @@ import { node_modules_external } from "./tools/externals.mjs"; import fs from "fs"; import cpy from "cpy"; +const EXTENSION = "../{{ module }}/extension"; + const BUNDLES = [ { entryPoints: ["src/ts/index.ts"], @@ -25,7 +27,7 @@ async function build() { } } } - fs.rmSync("../{{ module }}/extension", { + fs.rmSync(EXTENSION, { recursive: true, force: true, }); @@ -45,8 +47,8 @@ async function build() { await Promise.all(BUNDLES.map(bundle)).catch(() => process.exit(1)); // Copy servable assets to python extension (exclude esm/) - fs.mkdirSync("../{{ module }}/extension", { recursive: true }); - await cpy("dist/**/*", "../{{ module }}/extension", { + fs.mkdirSync(EXTENSION, { recursive: true }); + await cpy("dist/**/*", EXTENSION, { filter: (file) => !file.relativePath.startsWith("esm/") && !file.relativePath.startsWith("dist/esm/"),