m-ou-se / inline-python

Inline Python code directly in your Rust code
https://docs.rs/inline-python
BSD 2-Clause "Simplified" License
1.16k stars 40 forks source link

How to return value to Rust #17

Closed hyousefGopher closed 4 years ago

hyousefGopher commented 4 years ago

I wrote the below:

#![feature(proc_macro_hygiene)]
use inline_python::python;

fn main() {
    println!("Hello, Rust!");
    let max = 10;
    let mut z = 0;

    python! {
        import cv2

        print("Hello, Python")
        print(cv2.__version__)
        for x in range(1, 'max, 1):
            print(x)
        'z = 'max
    }
    println!("z = {}", z);
}

The variable max is sent correctly from Rust to Python, but the variable z is not modified in the Python code, it remains zero!

image

de-vri-es commented 4 years ago

The syntax 'var only allows you to use Rust values from Python, not vice-versa.

Retrieving values back from python is shorty described in the readme:

Getting information back

A Context object could also be used to pass information back to Rust, as you can retrieve the global Python variables from the context through Context::get_global.

More information can be found in the documentation for the Context struct.