rust cpython, is there any setup of the python environment to do?

Viewed 48

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(())
    }
}
1 Answers

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
Related