1 year ago

#329499

test-img

Hakase

How to use Python mehtod interactive with Rust?

I'm working with some code that need to execute python method in Rust with Pyo3, but I have some problem in sahring a Struct between rust and python.

pub struct Wallet {
    pub cash: i64
}

impl Wallet {
    pub fn get_money(&mut self, num: i64) {
            self.cash += num;
    }
}


pub trait Context {
    /// execute py func here
    pub fn on_calculation(&mut self, wallet: &mut Wallet) {
          //CALL PYTHON METHOD HERE (need to send wallet)
          //pyclass.on_calculation(wallet) ?????
    }

    /// execute py func here
    pub fn finish(&mut self, wallet: &mut Wallet) {}
}

pub struct App {
    pyclass: pyclass
    wallet: Wallet,
}

impl App {

    pub fn run(&mut self, mut context: impl Context) {
        for _i in 0..1000000 {
            context(&mut self.wallet);
        }
        context.finish(&mut self.wallet);
    }
    pub fn reset_wallet(&mut self) {
        self.wallet.cash = 0;
    }
}

fn main() {
    struct TestStrategy {}
    impl Context for TestStrategy;
    let w = Wallet { cash:0 };
    let app = App { wallet:w };
    let stra = TestStrategy {};
    app.run(stra);
    app.reset_wallet();

}

While in Python , I have a class to execute the user code like below:

class Context:
    def __init__():
        self.member = 999
    def on_calculation(self, wallet):
        if 1 > 0:
            wallet.get_money(10)
            
    def finish(self, wallet):
        print(wallet.cash)

I could send a function object or method with class to Rust as Py and call it, it's done.

Question: In my example, there is a struct called wallet, it has some variable and method need to be used in both python method on_calculation and rust struct App with in one instance of struct. How to achieve that? Because the origin type couldn't be used in python.

python

rust

wrapper

ffi

pyo3

0 Answers

Your Answer

Accepted video resources