【Rust 日报】2021-11-26 使用 PyO3 从 Python 调用 Rust

使用 PyO3 从 Python 调用 Rust

PyO3 让 Python 调用 Rust 代码变得容易。用户可以编写 Rust 库,并依靠 PyO3 和生态系统中maturin的支持工具的组合 PyO3 来编译 Rust 库并将其作为 Python 模块直接安装。其中 PyO3 可以在 Python 和 Rust 之间转换类型,并且可以通过一组宏轻松地将 Rust 函数导出到 Python。

  • https://saidvandeklundert.net/learn/2021-11-18-calling-rust-from-python-using-pyo3/

使用 Rust 和机器学习的无人机摄影测量尝试

文章作者用无人机拍了一张防水布的照片。使用基本的摄影测量法估计了图片的面积,使用机器学习对图像中的防水布进行了分割,得到的防水布面积为 3.86 m2,而实际面积为 3.96 m2(误差约为 4%)整个预估算法由 Rust 实现。

  • http://cmoran.xyz/writing/adventures_in_photogrammetry

使用 Bors 合并队列

合并队列是一个与您的版本控制系统(本文将重点关注git和 GitHub)集成的应用程序,它要求以原子方式合并代码更改,从而确保主分支始终包含经过全面测试的代码版本。许多工程团队和开源项目正在引入合并队列作为其工作流程的一部分。这篇文章探讨了使用合并队列的几个原因,并描述了如何设置 Bors,Rust 语言项目使用的合并队列实现。

  • https://kflansburg.com/posts/merge-queues/


来自每日 侯盛鑫,坏姐姐

社区学习交流平台订阅:

  • Rustcc 论坛:支持 rss

  • 微信语言中文社区号:Rust

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过使用`pyo3`库来将`Python`类方法导出到`Rust`,然后在`Rust`中调用这些方法。以下是一个例子: ```python # example.py class MyClass: def __init__(self, name): self.name = name def greet(self): print(f"Hello, {self.name}!") ``` ```rust // main.rs use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[pyclass] struct MyClass { name: String, } #[pymethods] impl MyClass { #[new] fn new(name: String) -> Self { Self { name } } fn greet(&self) -> PyResult<()> { Python::with_gil(|py| { let gil = pyo3::Python::acquire_gil(); let py = gil.python(); let locals = [("self", pyo3::PyObject::from(self))].into_py_dict(py); py.run("self.greet()", None, Some(&locals))?; Ok(()) }) } } #[pyfunction] fn create_my_class(name: String) -> PyResult<MyClass> { Ok(MyClass::new(name)) } #[pymodule] fn example(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<MyClass>()?; m.add_wrapped(wrap_pyfunction!(create_my_class))?; Ok(()) } fn main() -> PyResult<()> { Python::with_gil(|py| { let example_module = PyModule::new(py, "example")?; example_module.add_class::<MyClass>()?; example_module.add_wrapped(wrap_pyfunction!(create_my_class))?; let locals = [("example", example_module)].into_py_dict(py); py.run("import example", None, Some(&locals))?; let my_class = example_module .call("create_my_class", ("World",), None)? .extract::<MyClass>()?; my_class.greet()?; Ok(()) }) } ``` 这个例子中,我们使用`pyo3`库将`Python`类`MyClass`导出到`Rust`中。在`Rust`代码中,我们可以通过调用`MyClass`的`greet`方法来执行`Python`类中的`greet`方法。我们还编写了一个`Rust`函数`create_my_class`,用于创建`MyClass`实例并将其返回到`Python`。最后,我们在`Rust`中调用`Python`代码来创建`MyClass`实例,然后调用`greet`方法来打印出“Hello, World!”的消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值