Search code examples
pythonrustcpythonpython-cffi

Rust struct into PyObject in rust-cpython


I am using rust-cpython to write functions in Rust that is callable in Python.

I have an existing struct that is used as an output. How to I make this into a PyObject that rust-cpython can understand?

My struct looks like this:

struct Block {
    start: i32,
    stop: i32,
}

Solution

  • My compilation error said I needed to implement the ToPyObject trait on my struct. To represent my struct in one of the PyObject types, I decided to use a PyDict.

    I looked at how rust-cpython does it for HashMap and I just copied it over.

    impl ToPyObject for Block {
        type ObjectType = PyDict;
    
        fn to_py_object(&self, py: Python) -> PyDict {
            let dict = PyDict::new(py);
            dict.set_item(py, "start", self.start).unwrap();
            dict.set_item(py, "stop", self.stop).unwrap();
    
            dict
        }
    }
    

    This is kind of a hack but it allows me to pass data with named fields as keys.