#![allow(clippy::not_unsafe_ptr_arg_deref)]
use crate::{
simics_exception,
sys::{
SIM_call_python_function, SIM_run_python, SIM_source_python, VT_call_python_module_function,
},
AttrValue, Error, Result,
};
use raw_cstr::raw_cstr;
use std::{any::type_name, path::Path};
#[simics_exception]
pub fn source_python<P>(file: P) -> Result<()>
where
P: AsRef<Path>,
{
unsafe {
SIM_source_python(raw_cstr(
file.as_ref().to_str().ok_or_else(|| Error::ToString)?,
)?)
};
Ok(())
}
#[simics_exception]
pub fn run_python<S>(line: S) -> Result<AttrValue>
where
S: AsRef<str>,
{
Ok(unsafe { SIM_run_python(raw_cstr(line)?) }.into())
}
#[simics_exception]
pub fn call_python_function<S, I, T>(function: S, args: I) -> Result<AttrValue>
where
S: AsRef<str>,
I: IntoIterator<Item = T>,
T: TryInto<AttrValue>,
{
let args: Vec<AttrValue> = args
.into_iter()
.map(|a| {
a.try_into().map_err(|_| Error::ToAttrValueConversionError {
ty: type_name::<T>().to_string(),
})
})
.collect::<Result<Vec<_>>>()?;
let args: AttrValue = args.try_into()?;
let mut args = args.into();
Ok(unsafe { SIM_call_python_function(raw_cstr(function)?, &mut args as *mut _) }.into())
}
#[simics_exception]
pub fn call_python_module_function<S, I, T>(module: S, function: S, args: I) -> Result<AttrValue>
where
S: AsRef<str>,
I: IntoIterator<Item = T>,
T: TryInto<AttrValue>,
{
let args: Vec<AttrValue> = args
.into_iter()
.map(|a| {
a.try_into().map_err(|_| Error::ToAttrValueConversionError {
ty: type_name::<T>().to_string(),
})
})
.collect::<Result<Vec<_>>>()?;
let args: AttrValue = args.try_into()?;
let mut args = args.into();
Ok(unsafe {
VT_call_python_module_function(
raw_cstr(module.as_ref())?,
raw_cstr(function.as_ref())?,
&mut args as *mut _,
)
}
.into())
}