diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 04c99ff..9dd580e 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -27,6 +27,7 @@ jobs: - python - cython - cpp + - cpp-capi - js - jupyter - rust @@ -88,7 +89,7 @@ jobs: elif [[ "$RUNNER_OS" == "macOS" ]]; then brew install clang-format fi - if: matrix.template == 'cpp' || matrix.template == 'cppjswasm' + if: matrix.template == 'cpp' || matrix.template == 'cpp-capi' || matrix.template == 'cppjswasm' - name: Setup Node.js uses: actions-ext/node/setup@8bcebee998923fcc26f5854b4fd05ea378b58262 @@ -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 == 'rust-capi' || matrix.template == 'rustjswasm' + if: matrix.template == 'cpp' || matrix.template == 'cpp-capi' || matrix.template == 'cppjswasm' || matrix.template == 'rust' || matrix.template == 'rust-capi' || matrix.template == 'rustjswasm' diff --git a/Makefile b/Makefile index 14c7b8b..02991d5 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-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-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 @@ -52,6 +52,11 @@ gen-cpp: ## regenerate the c++ template from scratch copier copy -w . ../python-template-cpp --data-file examples/cpp.yaml cd ../python-template-cpp && $(SED) 's#_src_path: .#_src_path: https://github.com/python-project-templates/base.git#g' ./.copier-answers.yaml +gen-cpp-capi: ## regenerate the c++ template with a C ABI library from scratch + mkdir -p ../python-template-cpp-capi && cd ../python-template-cpp-capi && rm -rf ./* && rm -rf .copier-answers.yaml .gitignore .github .gitattributes + copier copy -w . ../python-template-cpp-capi --data-file examples/cpp-capi.yaml + cd ../python-template-cpp-capi && $(SED) 's#_src_path: .#_src_path: https://github.com/python-project-templates/base.git#g' ./.copier-answers.yaml + gen-js: ## regenerate the js template from scratch mkdir -p ../python-template-js && cd ../python-template-js && rm -rf ./* && rm -rf .copier-answers.yaml .gitignore .github .gitattributes copier copy -w . ../python-template-js --data-file examples/js.yaml @@ -102,7 +107,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-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 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 @@ -117,6 +122,13 @@ test-cpp: cd ../python-template-cpp && make checks cd ../python-template-cpp && make test +test-cpp-capi: + cd ../python-template-cpp-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-cpp-capi && make develop + cd ../python-template-cpp-capi && make lint + cd ../python-template-cpp-capi && make checks + cd ../python-template-cpp-capi && make test + test-js: cd ../python-template-js && 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-js && make develop diff --git a/README.md b/README.md index ccabe87..9850840 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ One selector chooses a template: - `Python / Pure` generates a pure Python package from `python/pure/`. - `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 / C++` generates a Python/C++ package with pybind11 bindings or standalone C++ code from `python/cpp/`. With `add_c_abi`, it also builds a C ABI library that the extension links against and wheels ship with its header. - `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/`. 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/`. diff --git a/copier.yaml b/copier.yaml index 6486eaa..85b7806 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 == 'rust' }}" + when: "{{ add_extension in ['cpp', 'rust'] }}" python_version_primary: type: str diff --git a/examples/cpp-capi.yaml b/examples/cpp-capi.yaml new file mode 100644 index 0000000..375c538 --- /dev/null +++ b/examples/cpp-capi.yaml @@ -0,0 +1,13 @@ +--- +add_c_abi: true +add_docs: true +add_pyodide: false +add_vcpkg: false +add_wiki: true +add_extension: cpp +email: 3105306+timkpaine@users.noreply.github.com +github: python-project-templates +project_description: A C++-Python project template with a C ABI library +project_name: python template cpp capi +python_version_primary: '3.11' +team: Python Project Template Authors diff --git a/examples/cpp.yaml b/examples/cpp.yaml index f22ab39..ec773f2 100644 --- a/examples/cpp.yaml +++ b/examples/cpp.yaml @@ -1,4 +1,5 @@ --- +add_c_abi: false add_docs: true add_pyodide: false add_vcpkg: true diff --git a/python/cpp/README.md.jinja b/python/cpp/README.md.jinja index 7e11b1c..38818d1 100644 --- a/python/cpp/README.md.jinja +++ b/python/cpp/README.md.jinja @@ -8,6 +8,31 @@ [![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 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/cpp/cpp/{% if add_c_abi %}CMakeLists.txt{% endif %}.jinja b/python/cpp/cpp/{% if add_c_abi %}CMakeLists.txt{% endif %}.jinja new file mode 100644 index 0000000..0db29f8 --- /dev/null +++ b/python/cpp/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/cpp/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}.pc.in.jinja b/python/cpp/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}.pc.in.jinja new file mode 100644 index 0000000..fba91bb --- /dev/null +++ b/python/cpp/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/cpp/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}Config.cmake.in.jinja b/python/cpp/cpp/{% if add_c_abi %}cmake{% endif %}/{{module}}Config.cmake.in.jinja new file mode 100644 index 0000000..d9edb54 --- /dev/null +++ b/python/cpp/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/cpp/cpp/{% if add_c_abi %}python{% endif %}/extension.cpp.jinja b/python/cpp/cpp/{% if add_c_abi %}python{% endif %}/extension.cpp.jinja new file mode 100644 index 0000000..69c5d70 --- /dev/null +++ b/python/cpp/cpp/{% if add_c_abi %}python{% endif %}/extension.cpp.jinja @@ -0,0 +1,9 @@ +#include + +#include "{{ module }}/{{ module }}.h" + +PYBIND11_MODULE(extension, m) { + m.doc() = "pybind11 example plugin"; + + m.def("add", &{{ module }}_add, "A function that adds two numbers"); +} diff --git a/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}c_api.cpp{% endif %}.jinja b/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}c_api.cpp{% endif %}.jinja new file mode 100644 index 0000000..634f8ac --- /dev/null +++ b/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}c_api.cpp{% endif %}.jinja @@ -0,0 +1,7 @@ +#include "{{ module }}/{{ module }}.h" + +#include "{{ project_name_formatted }}/example.hpp" + +uint32_t {{ module }}_abi_version(void) { return {{ module | upper }}_ABI_VERSION; } + +int32_t {{ module }}_add(int32_t i, int32_t j) { return {{ module }}::add(i, j); } diff --git a/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}example.cpp{% endif %}.jinja b/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}example.cpp{% endif %}.jinja new file mode 100644 index 0000000..ec91527 --- /dev/null +++ b/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}example.cpp{% endif %}.jinja @@ -0,0 +1,7 @@ +#include "{{ project_name_formatted }}/example.hpp" + +namespace {{ module }} { + +int add(int i, int j) { return i + j; } + +} diff --git a/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}example.hpp{% endif %}.jinja b/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}example.hpp{% endif %}.jinja new file mode 100644 index 0000000..887ac71 --- /dev/null +++ b/python/cpp/cpp/{{project_name_formatted}}/{% if add_c_abi %}example.hpp{% endif %}.jinja @@ -0,0 +1,7 @@ +#pragma once + +namespace {{ module }} { + +int add(int i, int j); + +} diff --git a/python/cpp/cpp/{{project_name_formatted}}/extension.cpp.jinja b/python/cpp/cpp/{{project_name_formatted}}/{% if not add_c_abi %}extension.cpp{% endif %}.jinja similarity index 100% rename from python/cpp/cpp/{{project_name_formatted}}/extension.cpp.jinja rename to python/cpp/cpp/{{project_name_formatted}}/{% if not add_c_abi %}extension.cpp{% endif %}.jinja diff --git a/python/cpp/cpp/{{project_name_formatted}}/extension.hpp b/python/cpp/cpp/{{project_name_formatted}}/{% if not add_c_abi %}extension.hpp{% endif %} similarity index 100% rename from python/cpp/cpp/{{project_name_formatted}}/extension.hpp rename to python/cpp/cpp/{{project_name_formatted}}/{% if not add_c_abi %}extension.hpp{% endif %} diff --git a/python/cpp/pyproject.toml.jinja b/python/cpp/pyproject.toml.jinja index 7121bda..47b64bc 100644 --- a/python/cpp/pyproject.toml.jinja +++ b/python/cpp/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 %}", "pybind11", ] build-backend = "hatchling.build" @@ -46,7 +46,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 %}", "hatchling", "mdformat", "mdformat-myst", @@ -82,7 +82,12 @@ replace = '__version__ = "{new_version}"' filename = "pyproject.toml" 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 = "{% if python_version_primary == '3.10' %}cp310-* {% endif %}{% if python_version_primary in ['3.10', '3.11'] %}cp311-* {% endif %}{% if python_version_primary in ['3.10', '3.11', '3.12'] %}cp312-* {% endif %}cp313-*" test-command = "pytest -vvv {project}/{{ module }}/tests" @@ -92,11 +97,16 @@ test-extras = "develop" manylinux-aarch64-image = "manylinux_2_28" manylinux-x86_64-image = "manylinux_2_28" 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"} 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] archs = "AMD64" skip = "*win32 *arm64" @@ -106,6 +116,10 @@ skip = "*win32 *arm64" test-command = "python -m pytest -vvv --pyargs {{ module }}.tests" test-extras = [] test-requires = ["pytest"] +{% if add_c_abi -%} +# Emscripten has no shared libraries to split; compile the library in. +environment = {HATCH_CPP_LIBRARY_SOURCE="direct"} +{% endif -%} {% endif %} [tool.coverage.run] branch = true @@ -127,9 +141,33 @@ src = "/" [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" +sources = ["cpp/python/extension.cpp"] +include-dirs = ["{{ module }}/include"] +binding = "pybind11" +depends = ["{{ module }}/lib/lib{{ module }}"] +{%- else %} libraries = [ {name = "{{ module }}/extension", sources = ["cpp/{{ project_name_formatted }}/extension.cpp"], include-dirs = ["cpp"], binding="pybind11"} ] +{%- endif %} [tool.hatch.build.targets.sdist] exclude = ["*.dll", "*.dylib", "*.so", "*.pyd"] @@ -148,6 +186,9 @@ artifacts = [ "{{ module }}/*.dll", "{{ module }}/*.dylib", "{{ module }}/*.so", +{%- if add_c_abi %} + "{{ module }}/lib/*", +{%- endif %} ] packages = [ "{{ module }}", diff --git a/python/cpp/{{module}}/__init__.py b/python/cpp/{{module}}/__init__.py deleted file mode 100644 index f661b47..0000000 --- a/python/cpp/{{module}}/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -import os -import os.path - -from .extension 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/cpp/{{module}}/__init__.py.jinja b/python/cpp/{{module}}/__init__.py.jinja new file mode 100644 index 0000000..824a373 --- /dev/null +++ b/python/cpp/{{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 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/cpp/{{module}}/tests/test_all.py.jinja b/python/cpp/{{module}}/tests/test_all.py.jinja index f3a6ba9..97a7aad 100644 --- a/python/cpp/{{module}}/tests/test_all.py.jinja +++ b/python/cpp/{{module}}/tests/test_all.py.jinja @@ -1,6 +1,111 @@ +{% 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 add, get_include, get_libraries, get_library_dirs + +C_CONSUMER = """ +#include +#include <{{ module }}/{{ module }}.h> + +int main(void) { + printf("%u %d", {{ module }}_abi_version(), {{ module }}_add(1, 2)); + 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_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" + + +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" +{%- else -%} from {{ module }} import add class TestAll: def test_all(self): assert 3 == add(1, 2) +{%- endif %} diff --git a/python/cpp/{{module}}/{% if add_c_abi %}include{% endif %}/{{module}}/{{module}}.h.jinja b/python/cpp/{{module}}/{% if add_c_abi %}include{% endif %}/{{module}}/{{module}}.h.jinja new file mode 100644 index 0000000..410a070 --- /dev/null +++ b/python/cpp/{{module}}/{% if add_c_abi %}include{% endif %}/{{module}}/{{module}}.h.jinja @@ -0,0 +1,28 @@ +/* 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 + +/* 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); + +#ifdef __cplusplus +} +#endif