簡體   English   中英

如何使用 PyO3 構建混合 Python Rust 包

[英]How to structure a mixed Python Rust package with PyO3

我正在尋找有關如何構建一個包含用 Rust 編寫的擴展模塊的 Python 包的信息,其中兩種語言是混合的。 我正在將 pyO3 用於 FFI,但似乎無法找到有關如何執行此操作的示例。 具體來說:我的 rust 庫公開了一個類型,該類型稍后由 python 類包裝。 只有 python 類應該為以后的用戶公開,並且包應該結構化,以便它可以推送到 PyPI。

例如:

在生銹的一面

#[pyclass]
pub struct Point {
    x: f64,
    y: f64 
}

#[pymethods]
impl Point {
    #[new]
    pub fn new(x: f64, y: f64) -> Self { Self{x, y} }
}

在蟒蛇方面

from ??? import Point

class Points:
    points: List[Point] 
    
    def __init__(self, points: List[Tuple[float, float]]):
        self.points = []
        for point in points:
            x, y = point
            self.points.append(Point(x, y))

我將感謝任何信息、來源、示例等!

我找到了一種使用 Maturin 做到這一點的方法。 因此,如果其他人試圖找出如何做到這一點,這是一種方法。

該項目需要具有以下結構:

my_project
├── Cargo.toml
├── my_project
│   ├── __init__.py
│   └── sum.py
└── src
    └── lib.rs

Cargo.toml 可以是:

[package]
name = "my_project"
version = "0.1.0"
edition = "2018"

[lib]
name = "my_project"
crate-type = ["cdylib"]

[dependencies.pyo3]
version = "0.14.5"
features = ["extension-module"]

lib.rs 的一個例子是:

use pyo3::prelude::*;

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

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

現在在 sum.py 中可以訪問該函數(在maturin develop過程中使用maturin develop后,以及在maturin build后自動發布時):

from .my_project import sum_as_string

class Sum:
    sum: str
    
    def __init__(self, lhs: int, rhs: int):
        self.sum = sum_as_string(lhs, rhs)

例如, _ init _.py 文件可以只公開 Sum 類:

from .sum import Sum

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM