将可变指针传递给函数而不先初始化它
Pass mutable pointer to function without initializing it first
use std::ptr::{addr_of_mut, null_mut};
use libc::{CLOCK_MONOTONIC, timer_create, timer_delete, timer_t};
fn main() {
let mut timer1: timer_t = null_mut();
unsafe {
let r = timer_create(CLOCK_MONOTONIC, null_mut(), addr_of_mut!(timer1));
if r == 0 {
timer_delete(timer1);
}
}
}
调用timer_create()
时,生成的计时器ID存储在变量timer1
中。我将它作为可变指针传递,所以这是输出变量。
我知道 API 保证它是安全的,如何避免像上面的代码那样将 timer1
初始化为 null_mut()
?
您可以使用 MaybeUninit
:
use std::mem::MaybeUninit;
use std::ptr::null_mut;
use libc::{CLOCK_MONOTONIC, timer_create, timer_delete, timer_t};
fn main() {
let mut timer1 = MaybeUninit::<timer_t>::uninit();
let timer1 = unsafe {
let r = timer_create(CLOCK_MONOTONIC, null_mut(), timer1.as_mut_ptr());
if r != 0 {
panic!("…");
}
timer1.assume_init()
};
unsafe {
timer_delete(timer1);
}
}
use std::ptr::{addr_of_mut, null_mut};
use libc::{CLOCK_MONOTONIC, timer_create, timer_delete, timer_t};
fn main() {
let mut timer1: timer_t = null_mut();
unsafe {
let r = timer_create(CLOCK_MONOTONIC, null_mut(), addr_of_mut!(timer1));
if r == 0 {
timer_delete(timer1);
}
}
}
调用timer_create()
时,生成的计时器ID存储在变量timer1
中。我将它作为可变指针传递,所以这是输出变量。
我知道 API 保证它是安全的,如何避免像上面的代码那样将 timer1
初始化为 null_mut()
?
您可以使用 MaybeUninit
:
use std::mem::MaybeUninit;
use std::ptr::null_mut;
use libc::{CLOCK_MONOTONIC, timer_create, timer_delete, timer_t};
fn main() {
let mut timer1 = MaybeUninit::<timer_t>::uninit();
let timer1 = unsafe {
let r = timer_create(CLOCK_MONOTONIC, null_mut(), timer1.as_mut_ptr());
if r != 0 {
panic!("…");
}
timer1.assume_init()
};
unsafe {
timer_delete(timer1);
}
}