Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call a pyfunction implemented in PyO3 from the same rust program #1572

Closed
qt2 opened this issue Apr 21, 2021 · 2 comments
Closed

Call a pyfunction implemented in PyO3 from the same rust program #1572

qt2 opened this issue Apr 21, 2021 · 2 comments

Comments

@qt2
Copy link

qt2 commented Apr 21, 2021

Is it possible to call a pyfunction implemented in PyO3 from the same rust program?
For example:

#[pyfunction]
fn one() -> f32 {
    1.
}

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    // I'd like to call the function like this:
    py.run("print(one())");
}

In a binary crate, it seems that the functions are not loaded automatically by the #[pyfunction] macro, but I couldn't find a way to load them manually either.

I use the latest stable versions of Rust and PyO3.

@qt2 qt2 changed the title How can I call Call a pyfunction implemented in PyO3 from the same rust program Apr 21, 2021
@messense
Copy link
Member

Take a look at pyo3::py_run

#[pyfunction]
fn one() -> f32 {
    1.
}

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let one = wrap_pyfunction!(one)(py).unwrap();
    pyo3::py_run!(py, one, "print(one())");
}

@qt2
Copy link
Author

qt2 commented Apr 21, 2021

@messense Thank you for your advice. It completely solved my problem.

@qt2 qt2 closed this as completed Apr 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants