Skip to content

关于《Python迷惑行为》的投稿(改) #14

Description

@BobbyCheng0518

功能描述

之前发过一遍这个issue,但是还没做好,现在做好了,再发一遍,并且我也编辑了前一次的issue,和现在这里一样

功能描述

在Python中,可以利用Maturin实现与Rust的交互,定义了一个get_sum函数并交给Python

Image

现在要把一个Rust程序包装成一个Python库,这样更改文件目录:

Image (忽略这张图消失的.venv文件夹)

打开pyproject.toml(不是Cargo.toml)文件,添加两行:

[tool.maturin]
python-source = "python" # 这样告诉Maturin Python源文件存在python文件夹里
Image

运行maturin develop(我这里用了release模式编译,所以加了参数--release),开始调试

Image

编译完成后,就可以写__init__.py了

from .matry1 import get_sum

__all__ = ["get_sum"]

写完后,maturin build构建

Image

打开wheels里的whl文件

Image

复制绝对路径,然后可以直接安装

PS C:\Users\HP> py -m pip install I:\BobbyCheng\Rust\Maturin\matryoshka_maturin\matry1\target\wheels\matry1-0.1.0-cp314-cp314-win_amd64.whl
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Processing I:\BobbyCheng\Rust\Maturin\matryoshka_maturin\matry1\target\wheels\matry1-0.1.0-cp314-cp314-win_amd64.whl
Installing collected packages: matry1
Successfully installed matry1-0.1.0
PS C:\Users\HP>

接下来可以直接用Python调用

Image

但是(开始迷惑),由于Rust是可以调用Python的,所以可以这样写(因为我用的是Python 3.14,旧版的pyo3不支持这个版本,所以用了0.29.0的版本,然而这个版本with_gil和import_bound都没了,如果用的是0.23.5的话,就和之前with_gil的方法一样了):

Image

这样就成功套了一层娃:

Image
use pyo3::prelude::*;

fn main() -> PyResult<()> {
    Python::attach(|py| {
        let matry1_mod = py.import("matry1")?;
        let result = matry1_mod.call_method("get_sum", (1, 2), None)?;
        let num: i32 = result.extract()?;
        println!("get_sum 返回: {}", num);
        Ok(())
    })
}

Cargo.toml下面加入:

[dependencies]
pyo3 = { version = "0.29.0", features = ["auto-initialize"] }

这还没完,再新建一个maturin项目,你甚至还可以这样:

Image Image Image Image

这样就成功用Python调用了Rust调用了Python调用了Rust

还能继续套(用Rust调用Python调用Rust调用Python调用Rust):

Image

......
再往后我就不叠了,但是理论上来说只要内存足够,可以无限套娃

附件

No response

附件

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions