Let's assume we have a software module with a data structure in Rust, which can do a specific computation taking a list of numbers as input. We would like to access this module from outside, e.g. C++. As the computation is processed number-by-number and each step takes time, we would like to count, how many numbers of the list have been processed thus far. This is stored inside an inner variable of the data structure.
Take e.g. the following source code in Rust:
pub struct Calculator {
result: i32,
steps: usize,
}
impl Calculator {
pub fn new() -> Self {
Calculator {
result: 0,
steps: 0
}
}
pub fn specific_computation(&mut self, numbers: Vec<f32>) {
for number in numbers.into_iter() {
// computation here
self.steps += 1;
}
}
}
Now we would like to draft a foreign function interface to trigger this computation from outside. As the computation takes time, we would also like to know, how many numbers have been processed while the computation is running.
#[no_mangle]
pub unsafe extern "C" fn create_calculator(calculator: &mut *mut Calculator) {
*calculator = Box::into_raw(Box::new(Calculator::new()));
}
#[no_mangle]
pub unsafe extern "C" fn do_specific_computation(calculator: *mut Calculator, numbers: *const u32, count: i32) -> f32 {
let numbers = std::slice::from_raw_parts(numbers as *const f32, count as usize);
let calculator = &mut *calculator;
calulator.specific_computation(numbers);
}
Is it possible to access the pointer calculator
from outside while the external function call specific_computation
is running so that the inner variable calculator.steps
can be read out?