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

2024-04-19 19:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找有关如何构造一个Python包的信息,该包封装了一个用Rust编写的扩展模块,这两种语言是混合的。我正在使用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} }
}

在python方面

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))

我将感谢任何信息,来源,例子等


Tags: 模块self信息类型newrustfloatpoints
1条回答
网友
1楼 · 发布于 2024-04-19 19:48:03

我找到了一种使用Durin的方法。 所以,如果有人想知道怎么做,这里有一个方法

项目需要具有以下结构:

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 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)

例如,uinit upy.py文件只能公开Sum类:

from .sum import Sum

相关问题 更多 >