Ada*_*dam 6 python ffi package rust pyo3
我正在寻找有关如何构建 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} }
}
Run Code Online (Sandbox Code Playgroud)
在蟒蛇方面
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))
Run Code Online (Sandbox Code Playgroud)
我将感谢任何信息、来源、示例等!
我找到了一种使用 Maturin 来做到这一点的方法。\n因此,如果其他人试图找出如何做到这一点,这里有一种方法。
\n该项目需要具有以下结构:
\nmy_project\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Cargo.toml\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 my_project\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 sum.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 lib.rs\nRun Code Online (Sandbox Code Playgroud)\nCargo.toml 可以是:
\n[package]\nname = "my_project"\nversion = "0.1.0"\nedition = "2018"\n\n[lib]\nname = "my_project"\ncrate-type = ["cdylib"]\n\n[dependencies.pyo3]\nversion = "0.14.5"\nfeatures = ["extension-module"]\nRun Code Online (Sandbox Code Playgroud)\nlib.rs 的一个示例是:
\nuse pyo3::prelude::*;\n\n#[pyfunction]\nfn sum_as_string(a: usize, b: usize) -> PyResult<String> {\n Ok((a + b).to_string())\n}\n\n#[pymodule]\nfn my_project(_py: Python, m: &PyModule) -> PyResult<()> {\n m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;\n Ok(())\n}\nRun Code Online (Sandbox Code Playgroud)\n现在在 sum.py 中可以访问该函数(在maturin develop开发期间使用后,以及在之后自动发布时maturin build):
from .my_project import sum_as_string\n\nclass Sum:\n sum: str\n \n def __init__(self, lhs: int, rhs: int):\n self.sum = sum_as_string(lhs, rhs)\nRun Code Online (Sandbox Code Playgroud)\n例如, _ init _.py 文件只能公开 Sum 类:
\nfrom .sum import Sum\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1057 次 |
| 最近记录: |