Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pyo3 python_calling_rust example #753

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions .bazelci/presubmit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ tasks:
- "//..."
- "-//ffi/rust_calling_c:matrix_dylib_test"
- "-//ffi/rust_calling_c:matrix_dynamically_linked"
- "-//ffi/python_calling_rust/..."
# The bindgen rules currently do not work on windows
# see: https://github.com/bazelbuild/rules_rust/issues/919
- "-//bindgen/..."
Expand Down
1 change: 1 addition & 0 deletions docs/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ bzl_library(
"@rules_rust//cargo:rules",
"@rules_rust//crate_universe:rules",
"@rules_rust//proto:rules",
"@rules_rust//python:rules",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is needed. Perhaps it should be removed unless we're going to be documenting some python rules in the root package.

"@rules_rust//rust:rules",
"@rules_rust//wasm_bindgen:rules",
],
Expand Down
4 changes: 4 additions & 0 deletions examples/WORKSPACE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ load("//sys:sys_deps.bzl", "sys_deps")

sys_deps()

load("@examples//ffi/python_calling_rust/raze:crates.bzl", "rules_rust_examples_ffi_python_calling_rust_fetch_remote_crates")

rules_rust_examples_ffi_python_calling_rust_fetch_remote_crates()

local_repository(
name = "rules_rust_example_cargo_manifest_dir",
path = "cargo_manifest_dir/external_crate",
Expand Down
29 changes: 29 additions & 0 deletions examples/ffi/python_calling_rust/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

load("@rules_python//python:defs.bzl", "py_test")
load("@rules_rust//python:py_rust_library.bzl", "py_rust_library")

py_rust_library(
name = "hello_py",
srcs = ["hello_py.rs"],
edition = "2018",
deps = ["//ffi/python_calling_rust/raze:pyo3"],
)

py_test(
name = "test",
srcs = ["test.py"],
deps = [":hello_py"],
)
14 changes: 14 additions & 0 deletions examples/ffi/python_calling_rust/hello_py.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}

#[pymodule]
fn hello_py(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;

Ok(())
}
4 changes: 4 additions & 0 deletions examples/ffi/python_calling_rust/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from ffi.python_calling_rust.hello_py import sum_as_string

assert sum_as_string(1, 1) == "2"
print("Ok!")
8 changes: 8 additions & 0 deletions python/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")

package(default_visibility = ["//visibility:public"])

bzl_library(
name = "rules",
srcs = glob(["**/*.bzl"]),
)
51 changes: 51 additions & 0 deletions python/py_rust_library.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
mfarrugi marked this conversation as resolved.
Show resolved Hide resolved
"""

load("@bazel_skylib//rules:copy_file.bzl", "copy_file")
load("@rules_python//python:python.bzl", "py_library")
load("@rules_rust//rust:rust.bzl", "rust_library")

def py_rust_library(name, **kwargs):
"""
Wraps a rust shared library that implements a python native extension to be usable by @rules_python targets.

Typically this is done through the use of a crate such as `pyo3` or `cpython`.

Args:
name (str): A unique name for this target.
**kwargs: Passed directly to rust_library.
"""

mangled = name + "_mangled_so"
rust_library(
name = mangled,
crate_type = "cdylib",
Copy link
Collaborator Author

@mfarrugi mfarrugi Sep 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One problem with this macro is that rules_rust doesn't have the equivalent of linkstatic = False as in the (naieve?) cc macro bazelbuild/bazel#701 (comment)

I suspect this is not as much of an issue for Rust since versions are mangled into symbols, but I'm not sure what happens if the same exact crate is statically linked into two separate python extensions that are then loaded into python.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mfarrugi@a483a7f illustrates the issue, and fails like so:

Traceback (most recent call last):
  File "/home/marco/.cache/bazel/_bazel_marco/9ec96d05a32431fe9b2731f854ff9adb/execroot/examples/bazel-out/k8-fastbuild/bin/ffi/python_calling_rust/test.runfiles/examples/ffi/python_calling_rust/test.py", line 12, in <module>
    assert s1 == s2, (s1, s2)
AssertionError: (-877036644, -885769300)

The same thing can happen with the cc macro linked above if there is a dependency that can only be linked statically. Fixing this pedantically would require each py_binary rule to link all of its native extensions at the same time (or require them to be fully dynamically linked), which is far beyond the scope of this PR.

rustc_flags = select({
"@rules_rust//rust/platform:osx": [
"--codegen=link-arg=-undefined",
"--codegen=link-arg=dynamic_lookup",
],
"//conditions:default": [],
}),
**kwargs
)

unix = name + "_unix"
copy_file(
name = unix,
src = mangled,
out = name + ".so",
)
windows = name + "_windows"
copy_file(
name = windows,
src = mangled,
out = name + ".pyd",
)
py_library(
name = name,
data = select({
"@rules_rust//rust/platform:windows": [windows],
"//conditions:default": [unix],
}),
)