我尝试通过静态变量在C回调中提供闭包。我已经能够使用
以下是我的代码:
Fn
类型使其正常运行,但我想通过 FnMut
使其更加灵活,以便为库的用户提供更多选择。以下是我的代码:
lazy_static! {
static ref CALLBACK: Mutex<RefCell<Box<FnMut(Result<&str>) + Send>>> = Mutex::new(RefCell::new(Box::new(|_|())));
}
fn wrap_cb<F: Fn(Result<&str>)>(f: Option<F>) -> Option<unsafe extern "C" fn(*mut c_char, size_t)> {
match f {
Some(_) => {
unsafe extern "C" fn wrapped(msg: *mut c_char, len: size_t) {
let s = std::str::from_utf8(std::slice::from_raw_parts(msg as *const u8, len))
.map_err(Error::from);
let x = CALLBACK.lock().unwrap();
x.borrow_mut()(s);
}
Some(wrapped)
}
None => None,
}
}
这会产生错误:
error[E0596]: cannot borrow immutable `Box` content as mutable
--> src/wpactrl.rs:56:17
|
56 | x.borrow_mut()(s);
| ^^^^^^^^^^^^^^ cannot borrow as mutable
Box<FnMut()>
不能直接调用。您需要将其转换为&mut FnMut()
。 - aSpexRefCell
。你可以使用(&mut *r)()
来调用闭包。 - aSpex