0

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?

Nevsden
  • 99
  • 6
  • 3
    If the computation's running, then the thread is being blocked and you can't do anything. If you want to do something, then spawn a separate thread to do the computation (you might also want to switch the `usize` to [`AtomicUsize`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html)). – Aplet123 Jun 16 '21 at 13:32
  • Thank you for insights! Based on your answer I am not sure if I have clearly expressed myself. The idea is: Whilst the computation is running from extern calling `do_specific_computation` I would like to access the `Calculator` object that has been handed over and read out its inner variable `steps`. It is clear to me that I need to spawn a separate thread for that. It is not clear to me, if I can actually access the `Calculator` object that easily while the function `do_specific_computation` is running. – Nevsden Jun 16 '21 at 15:18

0 Answers0