How to Call PyTorch from Rust via FFI
You cannot call PyTorch directly from Rust via FFI because PyTorch is a C++ library with no stable C API; you must use a Rust binding crate like pyo3 to call Python PyTorch or torch-sys to call the C++ core. Use pyo3 to run Python code from Rust, which is the standard approach for accessing PyTorch models.
use pyo3::prelude::*;
#[pyfunction]
fn run_pytorch_model(py: Python) -> PyResult<f64> {
let torch = py.import("torch")?;
let model = torch.getattr("load")?.call1(("model.pt",))?;
// Call model inference here
Ok(0.95)
}
#[pymodule]
fn my_module(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(run_pytorch_model, m)?)?;
Ok(())
}
Add pyo3 = { version = "0.20", features = ["extension-module"] } to your Cargo.toml.