From 3aca7751c04218886ba42b32196429774b3cfb17 Mon Sep 17 00:00:00 2001 From: Paul Wankadia Date: Fri, 1 Mar 2024 16:40:31 +0000 Subject: [PATCH] Make `pybind_extension()` work on Windows. Fixes #74. --- MODULE.bazel | 1 + README.md | 4 ++-- build_defs.bzl | 27 +++++++++++++++++++++++++-- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index fafb6a1..bd5228e 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -4,6 +4,7 @@ module( version = "2.11.1.bzl.2", ) +bazel_dep(name = "bazel_skylib", version = "1.5.0") bazel_dep(name = "platforms", version = "0.0.8") bazel_dep(name = "rules_cc", version = "0.0.9") bazel_dep(name = "rules_python", version = "0.31.0") diff --git a/README.md b/README.md index e36230d..f165843 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ Provided rules: - `pybind_extension`: Builds a python extension, automatically adding the - required build flags and pybind11 dependencies. It defines a `*.so` target - which can be included as a `data` dependency of a `py_*` target. + required build flags and pybind11 dependencies. It defines a target which + can be included as a `data` dependency of a `py_*` target. - `pybind_library`: Builds a C++ library, automatically adding the required build flags and pybind11 dependencies. This library can then be used as a dependency of a `pybind_extension`. The arguments match a `cc_library`. diff --git a/build_defs.bzl b/build_defs.bzl index c71642f..cdbcdf0 100644 --- a/build_defs.bzl +++ b/build_defs.bzl @@ -5,6 +5,8 @@ """Build rules for pybind11.""" +load("@bazel_skylib//rules:copy_file.bzl", "copy_file") + def register_extension_info(**kwargs): pass @@ -24,8 +26,15 @@ PYBIND_DEPS = [ ] # Builds a Python extension module using pybind11. -# This can be directly used in python with the import statement. -# This adds rules for a .so binary file. +# This can be directly used in Python with the import statement. +# Assuming the name NAME, the following targets will be defined: +# 1. NAME.so - the shared/dynamic library for the extension module +# 2. NAME.pyd - a copy of NAME.so named for Python on Windows; see +# https://github.com/pybind/pybind11_bazel/issues/74 +# 3. NAME - an alias pointing to either NAME.so or NAME.pyd as per +# the platform OS (not-Windows or Windows, respectively) +# Generally, the user will "depend" on this extension module via the +# data attribute of their py_* target; specifying NAME is preferred. def pybind_extension( name, copts = [], @@ -55,6 +64,20 @@ def pybind_extension( **kwargs ) + copy_file( + name = name + "_copy_so_to_pyd", + src = name + ".so", + out = name + ".pyd", + ) + + native.alias( + name = name, + actual = select({ + "@platforms//os:windows": name + ".pyd", + "//conditions:default": name + ".so", + }), + ) + # Builds a pybind11 compatible library. This can be linked to a pybind_extension. def pybind_library( name,