0

I'm able to expose simple functions written in Rust to python using pyo3 but can see no way to expose complex "eigen" / matrix types. Does anyone know if this is possible?

lib.rs

extern crate nalgebra as na;    
use pyo3::prelude::*;
use na::{SMatrix, Vector3, Matrix3};

/// Formats the sum of two numbers as string.
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
    Ok((a + b).to_string())
}


#[pyfunction]
fn matrix_math(v3: Vector3<f64>, m3x3: Matrix3<f64>) -> PyResult<SMatrix<f64, 3, 1>>{
    let mxv = m3x3 * v3;
    Ok(mxv)
}

// Neiter way works

type Matrix3f = Matrix3<f64>;
type Vector3f = Vector3<f64>;

#[pyfunction]
fn matrix_math_w_types(v3: Vector3f, m3x3: Matrix3f) -> PyResult<SMatrix<f64, 3, 1>>{
    let mxv = m3x3 * v3;
    mxv
}

#[pymodule]
fn libpytest(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    m.add_function(wrap_pyfunction!(matrix_math, m)?)?;

    Ok(())
}
sbeskur
  • 2,260
  • 23
  • 23
  • I don't know PyO3, but I suspect that the issue is that it can't expose generic types. Try to create a type alias, e.g. `type Matrix3f = Matrix3`, and expose that to your Python API. – Jmb Nov 24 '21 at 08:29
  • @Jmb Thanks, it was worth a try but no joy. I was hoping it would work like the pybind11 stuff in C++ that includes eigen vector / matrix types. I suspect there is a way but will need to keep searching. – sbeskur Nov 26 '21 at 16:35
  • You would need to have a type alias also for the return type, or convert the `SMatrix` into a `Vector3f` and return that. – Jmb Nov 26 '21 at 18:48
  • @Jmb yes. I did try that as well but it seems that pyo3 just does not support nalgebra bindings. Looks like they do support ndarray which I have not explored. Eigen is the defacto matrix lib for C++ but I gather that ndarray is the defactor matrix library for Rust. Thank you again for your response. – sbeskur Nov 29 '21 at 15:20

0 Answers0