Rust Cpython,是否有Python环境的设置?

发布于 2025-02-08 19:28:57 字数 1309 浏览 2 评论 0 原文

我正在遵循此示例,以将Rust写入python App的函数导入: https://depth-first.com/articles/2022/03/09/python-extensions-in-python-extension in

输出是'libfunction.dylib',我应该将其重命名为'function.so',将其移至文件夹中,然后我应该能够在python中导入它(例如该模块只是公开一个称为entry的函数):

from function import greet

我缺少的python环境设置了一些设置吗?即使我完全使用文章链接的存储库,python也找不到模块(检查了正确拼写的10次,该文件在正确的文件夹中等等。):

ModuleNotFoundError: No module named function

货物

[package]
name = "function"
version = "0.1.0"
edition = "2021"

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

[dependencies]
cpython = "0.7"

[features]
default = ["python3"]
python3 = ["cpython/python3-sys", "cpython/extension-module"]

。 .rs:

use cpython::{py_module_initializer, py_fn, PyResult, Python};

fn greet(_: Python, name: String) -> PyResult<String> {
    Ok(format!("Hello, {}!", name))
}

py_module_initializer! {
    function, |py, module| {
        module.add(py, "greet", py_fn!(py, greet(string: String)))?;

        Ok(())
    }
}

I'm following through this example for importing a function written in Rust into a python app: https://depth-first.com/articles/2022/03/09/python-extensions-in-pure-rust-with-rust-cpython/

the output is 'libfunction.dylib', which I should rename to 'function.so', move it to the folder where there's the python app.py, then I should be able to import it in python like (say that the module is just exposing a function called greet):

from function import greet

Is there some setup of the python environment that I'm missing? Even when I use exactly the repository linked by the article, python can't find the module (checked 10 times that the names are spelled correctly, the file is in the right folder etc..):

ModuleNotFoundError: No module named function

The cargo.toml would be

[package]
name = "function"
version = "0.1.0"
edition = "2021"

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

[dependencies]
cpython = "0.7"

[features]
default = ["python3"]
python3 = ["cpython/python3-sys", "cpython/extension-module"]

the lib.rs:

use cpython::{py_module_initializer, py_fn, PyResult, Python};

fn greet(_: Python, name: String) -> PyResult<String> {
    Ok(format!("Hello, {}!", name))
}

py_module_initializer! {
    function, |py, module| {
        module.add(py, "greet", py_fn!(py, greet(string: String)))?;

        Ok(())
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2025-02-15 19:28:57

As suggested in this issue,
the py_module_initializer!{function, ...} macro generates a module export function named PyInit_function, and the shared object name must match it.
Rename libfunction.so to function.so and import like this:

from function import greet
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文