Skip to content

Commit 340816d

Browse files
committed
Add direct member access to example
In the example demonstrating how to call between rust and python add direct member access.
1 parent 445cb6c commit 340816d

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

examples/call_between_rust_and_python.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ def __init__(self, name):
77
def python_callback():
88
python_person = PythonPerson("Peter Python")
99
rust_object = rust_function(42, "This is a python string", python_person)
10+
print("Printing member 'numbers' from rust struct: ", rust_object.numbers)
1011
rust_object.print_in_rust_from_python()
1112

1213
def take_string(string):

examples/call_between_rust_and_python.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ pub fn main() {
3030
#[pymodule]
3131
mod rust_py_module {
3232
use super::*;
33+
use rustpython_vm::{builtins::PyList, convert::ToPyObject, PyObjectRef};
3334

3435
#[pyfunction]
3536
fn rust_function(
@@ -45,16 +46,35 @@ string: {},
4546
python_person.name: {}",
4647
num, s, python_person.name
4748
);
48-
Ok(RustStruct)
49+
Ok(RustStruct {
50+
numbers: NumVec(vec![1, 2, 3, 4]),
51+
})
52+
}
53+
54+
#[derive(Debug, Clone)]
55+
struct NumVec(Vec<i32>);
56+
57+
impl ToPyObject for NumVec {
58+
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
59+
let list = self.0.into_iter().map(|e| vm.new_pyobj(e)).collect();
60+
PyList::new_ref(list, vm.as_ref()).to_pyobject(vm)
61+
}
4962
}
5063

5164
#[pyattr]
5265
#[pyclass(module = "rust_py_module", name = "RustStruct")]
5366
#[derive(Debug, PyPayload)]
54-
struct RustStruct;
67+
struct RustStruct {
68+
numbers: NumVec,
69+
}
5570

5671
#[pyclass]
5772
impl RustStruct {
73+
#[pygetset]
74+
fn numbers(&self) -> NumVec {
75+
self.numbers.clone()
76+
}
77+
5878
#[pymethod]
5979
fn print_in_rust_from_python(&self) {
6080
println!("Calling a rust method from python");

0 commit comments

Comments
 (0)