What’s the memory management strategy when using PyO3?

Viewed 90

I am a beginner to Rust and PyO3, I read the PyO3 User Guide and got some information as shown below:

  1. When Rust calls Python, the memory of Python part is allocated in Python heap and is taken care by the Python garbage collector.
  2. When Python calls rust, the arguments of rust functions can be either rust type or python native type, the former will incur a conversion but it's faster, the later is almost zero-cost.
  3. Rust can access python heap through reference, PyCell is always allocated in the Python heap, Rust doesn't have ownership of it, but Rust can benefit from it's interior mutability pattern.

But I still have the following questions

  1. How is memory passed/copied in multiple data interaction scenarios?

    a. When Python calls Rust

    i. Python passes some arguments to Rust func
    
    ii. Rust func creates some data and return to python
    
    iii. rust accepts arguments from python, do some calculation and return to Python
    

    b. When Rust calls Python

    i. Rust passes some arguments to Python func
    
    ii. Python func creates some data and return to python
    
    iii. Python accepts arguments from Rust, do some calculation and return to Rust
    
  2. If I create a PyCell with a Rust value which implements Into< PyClassInitializer >, will there be a memory copy?

  3. When Python calls Rust, does the conversion from Python Native Type to Rust Type mean that there is a memory copy from Python heap to rust heap?

0 Answers
Related