I'm trying to keep track of the number of instances of my C wrapper have been initialized.
I'm using std::sync::Once
to initialize the C library a single time and I need to be able to call terminate
once all instances have gone out of scope.
Currently, I have
static INSTANCES: usize = 0;
static mut VERSION: i32 = 0;
static GPIO_INIT: Once = ONCE_INIT;
fn init_gpio_lib() -> i32 {
println!("GPIOs initialized.");
64
}
fn terminate_gpio_lib() {
println!("GPIO lib terminated!");
}
struct GPIO {
version: i32
}
impl GPIO {
fn init() -> GPIO {
GPIO_INIT.call_once(|| {
unsafe {
VERSION = init_gpio_lib();
}
});
unsafe {
INSTANCES += 1;
}
unsafe {
GPIO {
version: VERSION
}
}
}
fn terminate(&mut self) {
unsafe {
INSTANCES -= 1;
if INSTANCES == 0 {
terminate_gpio_lib();
}
}
}
}
impl Drop for GPIO {
fn drop(&mut self) {
self.terminate();
}
}
I'm trying to make it safe, but I can't figure out how. The two things I've tried are
static INSTANCES: Mutex<usize> = Mutex::new(0)
In this case, I can't callMutex::new(0)
here.lazy_static!{ static ref INSTANCES: Mutex<usize> = Mutex::new(0) }
In this case, I can't useINSTANCES
inside of a struct function call.